Skip to content

Instantly share code, notes, and snippets.

@oslego
Last active August 29, 2015 14:02
Show Gist options
  • Save oslego/333f8d5849750e8aa58b to your computer and use it in GitHub Desktop.
Save oslego/333f8d5849750e8aa58b to your computer and use it in GitHub Desktop.
Cycle through data request strategies (ajax, jsonp) within a Promise.
function get(url){
return new Promise(function(resolve, reject){
// request strategies: ajax, jsonp
var types = ['json', 'jsonp'];
function call(){
// try data type strategies one-by-one; mutates the array
var type = types.shift();
// no more strategies left; give up and reject the promise
if (!type) {
reject();
return;
}
$.ajax({
url: url,
dataType: type,
method: 'GET',
success: function(resp){ resolve(resp) },
error: function(){ call() }
});
}
// attempt the first strategy
call();
});
}
function show(data){
console.log(data)
}
get('http://localhost:5000/v1/rates/eur')
.then(show)
.catch(function(){
console.log('all request strategies have failed')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment