Last active
August 29, 2015 14:02
-
-
Save oslego/333f8d5849750e8aa58b to your computer and use it in GitHub Desktop.
Cycle through data request strategies (ajax, jsonp) within a Promise.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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