Created
June 20, 2014 12:41
-
-
Save chrisbuttery/955a2c48d1b2fcc7e9e1 to your computer and use it in GitHub Desktop.
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
var promise = getPromise('http://api.icndb.com/jokes/random') | |
promise.then(function(data) { | |
console.log('Got data! Promise fulfilled.'); // 1st request finished | |
// 2nd request | |
return getPromise('http://api.icndb.com/jokes/random'); | |
}).then(function(result) { | |
console.log('the final result'); | |
}); | |
// or | |
var promise = getPromise('http://api.icndb.com/jokes/random') | |
promise.then(function(data) { | |
console.log('Got data! Promise fulfilled.'); // 1st request finished | |
// 2nd request | |
return getPromise('http://api.icndb.com/jokes/random'); | |
}, function(error) { | |
console.log('Promise rejected.'); | |
console.log(error.message); | |
}).then(function(result) { | |
console.log('the final result'); | |
}); |
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 getPromise(url) { | |
return promise = new Promise(function(resolve, reject) { | |
var request = new XMLHttpRequest(); | |
request.open('GET', url); | |
request.onload = function() { | |
if (request.status == 200) { | |
resolve(request.response); // we got data here, so resolve the Promise | |
} else { | |
reject(Error(request.statusText)); // status is not 200 OK, so reject | |
} | |
}; | |
request.onerror = function() { | |
reject(Error('Error fetching data.')); // error occurred, reject the Promise | |
}; | |
request.send(); //send the request | |
}); | |
console.log('Asynchronous request made.'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment