Created
May 31, 2017 05:45
-
-
Save vaz/eb7ef240105a578f1c55689955b57386 to your computer and use it in GitHub Desktop.
Promise example - chaining and parallel execution
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
// Promises example | |
// | |
// just a helper, which returns a promise that resolves after | |
// 500-1000 milliseconds with whatever `args` were passed in | |
function fakeKnex(...args) { | |
return new Promise((resolve, reject) => { | |
setTimeout( | |
function() { resolve(...args) }, | |
500 + (Math.floor(Math.random() * 500))) | |
}) | |
} | |
// example items | |
const ITEMS = [ | |
{ orderItem: 1 }, | |
{ orderItem: 2 }, | |
{ orderItem: 3 }, | |
{ orderItem: 4 }, | |
{ orderItem: 5 }, | |
] | |
// TIPS: | |
// - Promises in sequence: return value of `then` callback is another promise. | |
// - Promises in parallel: use `Promise.all` | |
// "insert user" with promise-chaining and Promise.all | |
fakeKnex({ some: 'user' }) | |
.then(userResult => { | |
console.log(userResult) | |
// insert order | |
return fakeKnex({ some: 'order' }) | |
}) | |
.then(orderResult => { | |
console.log(orderResult) | |
// Promise.all(promises) - takes an array of promises, and returns a new | |
// promise, which resolves only when each given promise has resolved. | |
// It resolves with an array of values, one for each promise. | |
return Promise.all(ITEMS.map(item => fakeKnex(item))) | |
}) | |
.then(itemsResults => { | |
console.log('order items:') | |
itemsResults.forEach(result => { | |
console.log(result) | |
}) | |
console.log("Redirect to /") | |
}) | |
.catch(console.error) | |
// the original version of the above code: | |
if (false) { | |
fakeKnex({ some: 'user' }) | |
.then(userResult => { | |
console.log(userResult) | |
// insert order | |
fakeKnex({ some: 'order' }) | |
.then(orderResult => { | |
console.log(orderResult) | |
// not sure how to do in parallel: | |
ITEMS.forEach(item => { | |
// not able to check the results | |
fakeKnex(item).then(() => {}) | |
}) | |
// this happens before the items are actually added: | |
console.log("Redirect to /") | |
}) | |
}) | |
// no catch() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment