Skip to content

Instantly share code, notes, and snippets.

@chrisbuttery
Created June 20, 2014 12:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisbuttery/955a2c48d1b2fcc7e9e1 to your computer and use it in GitHub Desktop.
Save chrisbuttery/955a2c48d1b2fcc7e9e1 to your computer and use it in GitHub Desktop.
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');
});
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