简体   繁体   English

如何使用async.js中的Promise进行编码?

[英]How to code with Promise from async.js?

Background 背景

I usually write node.js script based on async.js to control the work flow. 我通常会基于async.js编写node.js脚本来控制工作流程。 Sometimes I found that based on async.js, the code seems still a 'hell'. 有时我发现基于async.js,代码似乎仍然是“地狱”。 With multiple nest the code is not readable and tricky to maintain. 带有多个嵌套,代码不可读且难以维护。 I did some search here and found some useful resources - but most of them are general concepts. 我在这里进行了一些搜索,发现了一些有用的资源-但其中大多数是通用概念。 So I am going to ask a question. 所以我要问一个问题。 Any feedback would be appreciated. 对于任何反馈,我们都表示感谢。

My common code 我的通用代码

var request = require('request');
var async = require('async');

var array = [1, 2, 3, 4 ,5 ,6];
var url = 'http://www.google.com';
async.mapLimit(array, 3, function(number, callback) {
       request(url + number, function(error, res, body){
                  //do sth
                 callback();
       });
}, function(err){//do nothing});

Question

So this time I want to replace this kind of code by Promise. 所以这次我想用Promise代替这种代码。 Could you please help? 能否请你帮忙? If the question is duplicated, please suggest some useful resource url. 如果问题重复,请提出一些有用的资源网址。 Thanks! 谢谢!

You will need to Promisify request , which can be done with native promises, but since you're using NodeJS, it would be preferable if you used the Bluebird promise library, which is almost strictly superior to the native implementation. 您将需要Promisify request ,这可以通过本机Promise来完成,但是由于您使用的是NodeJS,因此,如果您使用Bluebird Promise库,则它最好比本机实现更严格。

Then you can do: 然后,您可以执行以下操作:

const Promise = require('bluebird');
const requestAsync = Promise.promisify(request); // This is what bluebird saves you
// requestAsync returns a promise instead of accepting a callback.

const array = [1, 2, 3, 4, 5, 6];

const requestSingle = number => requestAsync(`${url}${number}`);

Promise.map(array, requestSingle, {concurrency: 3});

Note that Promise.map() is a Bluebird functionality, and not native. 请注意, Promise.map()是Bluebird的功能,而不是本机的。

The closest you can easily get with native is: 使用Native可以轻松获得的最接近的是:

const arrayOfRequestPromises = array.map(requestSingle);

Promise.all(arrayOfRequestPromises)
  .then(allResults => {
    // do something
  })
  .catch(err => {
    // handle errors
  });

But then you lose the maximum 3 concurrent requests option. 但是,您将丢失最大3个并发请求选项。

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

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