Skip to content

Instantly share code, notes, and snippets.

@jmsevold
Last active April 14, 2016 22:18
Show Gist options
  • Save jmsevold/d0e7c379d08e7bfa94a1 to your computer and use it in GitHub Desktop.
Save jmsevold/d0e7c379d08e7bfa94a1 to your computer and use it in GitHub Desktop.
Promise example
var p = new Promise(function(resolve, reject) {
if(1 === 1) { // set 1===2 to make it fail
resolve('Success!');
}
else {
reject('Failure!');
}
});
p.then((success) => console.log(success), (fail) => console.log(fail));
// .then takes two callbacks. the first has an argument that will be the successful result, and the second has an argument that will be the reason for failure.
// chaining catch after then is the same as passing a second callback to .then to handle the error.
var p = new Promise(function(resolve, reject) {
// A mock async action using setTimeout
setTimeout(function() { reject('Done!'); }, 1000);
});
// the same as...
p.then(function(e) { console.log('done', e); })
.catch(function(e) { console.log('catch: ', e); });
p.then(function(e) { console.log('done', e); },function(e) { console.log('catch: ', e); })
var data =[
{ id: 0, name: 'Luke Skywalker' },
{ id: 1, name: 'Batman' },
{ id: 2, name: 'Boba Fett' }
];
var promise = new Promise(function(resolve,reject){
setTimeout(function(){ resolve(data); },4000);
});
promise.then(function(data){
console.log(data);
}).catch(function(error){
console.log(error);
});
var promise2 = new Promise(function(resolve, reject) {
if (1===2) {
resolve("Stuff worked!");
}
else {
reject("this shit didnt work");
}
});
promise2.then(function(data){
console.log(data);
}).catch(function(error){
console.log(error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment