Using await (a newer ES2017 technology that is built on generators in ES6), and assuming, as you've said:
- you have multiple items (in this case
['apple', 'peach', 'banana']
)
- you wish to perform some async operation on them
- You wish to avoid callbacks and
.then()
(which is a good idea if you're on node 7+ or current browsers)
Then:
var doThing = async function (input) {
return new Promise(function(resolve, reject) {
setTimeout(function(){
resolve(`Result for ${input}`)
}, 2000);
});
}
var start = async function(listOfThings){
var result = await Promise.all(listOfThings.map(doThing))
console.log('All done', result)
}
start(['apple', 'peach', 'banana'])
Will return:
All done [ 'Result for apple', 'Result for peach', 'Result for banana' ]
To get some data from the network instead, you can simply replace the the setTimeout
with superagent
or (if you want to write your own query string encoding, URL handling etc) fetch
.