简体   繁体   中英

async js code using generators

I need to proces some data. I can do it in sync and async way like this (simplified):

  1. sync way:

     for (var i in input) { result += input[i] } 
  2. async way

     function f(input,cb) { var result; if (!input) { setTimeout(function() {cb(result)},500); } else { f(input.slice(1),function(r) { result+=input[0]; }); } } 

Is it possible to rewrite async code using generators? I wish I had some For loop code instead of recursion.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM