简体   繁体   English

使用生成器异步js代码

[英]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. 我希望我有一些For循环代码,而不是递归代码。

Using await (a newer ES2017 technology that is built on generators in ES6 ), and assuming, as you've said: 使用await (一种基于ES6中的生成器的更新的ES2017技术),并假设,如您所说:

  • you have multiple items (in this case ['apple', 'peach', 'banana'] ) 您有多个项目(在本例中为['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() (如果您使用的是节点7+或当前的浏览器,则是个好主意)

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 . 要从网络获取一些数据,您可以简单地将setTimeout替换为superagent或(如果要编写自己的查询字符串编码,URL处理等) fetch

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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