Skip to content

Instantly share code, notes, and snippets.

@santiago-puch-giner
Last active May 5, 2016 22:18
Show Gist options
  • Select an option

  • Save santiago-puch-giner/5f7152375b5fee77905ae1a69f73f998 to your computer and use it in GitHub Desktop.

Select an option

Save santiago-puch-giner/5f7152375b5fee77905ae1a69f73f998 to your computer and use it in GitHub Desktop.
Promises in Javascript ES6
// Snippet for Promises (ES6)
// Create a Promise that is resolved and handle it using "then" methods
let p = new Promise( (resolve, reject) => {
setTimeout( () => {
resolve("Good to go!");
}, 1000);
});
p.then(
(data) => {
console.log(data);
},
(err) => {
console.log(err);
}
);
// Create a Promise that is rejected and handle it using "then" and "catch" methods
// Here we can see that, even if we have a resolve and a reject, if the promise
// has already changed to a "resolved" or "rejected" state it cannot change
// its state any more. That's why we only see the rejected value.
let p2 = new Promise( (resolve, reject) => {
setTimeout( () => {
resolve("Good to go!");
}, 1000);
setTimeout( () => {
reject("Oops that didn't go well...");
}, 500);
});
p2.then( (data) => {
console.log(data);
}).catch( (err) => {
console.log(err);
});
// Handle the resolved state of several promises
Promise.all([p, p2])
.then( (data) => {
console.log(data);
})
.catch( (err) => {
console.log(err);
});
// Visit https://promisesaplus.com/ for more information
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment