Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Promise example - chaining and parallel execution
// 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
You can’t perform that action at this time.