Skip to content

Instantly share code, notes, and snippets.

@vaz
Created April 19, 2017 22:06
Show Gist options
  • Save vaz/48a568bb4a62215b33552ffda77cb633 to your computer and use it in GitHub Desktop.
Save vaz/48a568bb4a62215b33552ffda77cb633 to your computer and use it in GitHub Desktop.
promises are fun.
// this is coming from a library
function delayedValue(x) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(x), 1000)
})
}
// module doQuery.js
function doQuery() {
return delayedValue({
name: 'my result',
values: [1, 2, 3, 4, 5],
}).then(result => {
if (result.error) {
throw new Error('doQuery error: ' + result.error)
}
console.log('doQuery: result is: ', result)
return result
})
}
function subQuery(value) {
return delayedValue(value * value)
}
// module.exports = { doQuery };
// elsewhere:
// const doQuery = require('doQuery')
var p1 = doQuery()
p1
.then(x => {
x['abc'] = 123
console.log(x)
return x
})
.then(x => {
const promises = x.values.map(value => subQuery(value))
return Promise.all(promises)
})
.catch(error => {
console.error('did query, got error', error)
return { name: 'foo' }
})
.then(values => {
for (let value of values) {
console.log('value: ', value)
}
})
// p1.then(x => {
// console.log('this is the other one')
// })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment