promises are fun.
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
// 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