Node.js(ES6)-Promise.all的控制流

Ben

我正在尝试创建一个处理并行HTTP请求的队列。

为每个HTTP请求生成一个请求对象,例如

{
    method: 'POST',
    uri: 'http://posttestserver.com/post.php',
    body: {
        some: 'foo'
    },
    json: true
}

我传入了这些对象的数组,希望将它们添加到队列中,然后执行实际的请求。

问题:Promise.all语句在返回之前等待所有请求完成。

问题:我希望将所有任务添加到队列中,并在每个请求完成后返回,而不是等待所有任务。谁能建议如何将发出请求的逻辑与将任务添加到队列分开?

注意:promise-queue和request-promise都返回promise。

这是我所拥有的:

"use strict";

const Queue = require("promise-queue");
const rp = require('request-promise');

const maxConcurrent = 10;
const maxQueue = Infinity;
const queue = new Queue(maxConcurrent, maxQueue);

var options = [
    {
        method: 'POST',
        uri: 'http://posttestserver.com/post.php',
        body: {
            some: 'foo'
        },
        json: true
    },{
        method: 'POST',
        uri: 'http://posttestserver.com/post.php',
        body: {
            some: 'bar'
        },
        json: true
    }
];

Promise.all(options.map(function(task) {
        return queue.add(function() {
            return rp(task);
        })
    }))
    .then(function(response) {
        log(response);
    })
    .catch(function(err) {
        log(err);
    });


function log(data) {
    console.log(JSON.stringify(data, undefined, 4));
}
whi

我建议在forEach循环中调用promise链,如下所示:

var queueTask = function(task) {
  // returns a promise
  return queue.add(function() { return rp(task); });
};

var logResponse = function(response) {
  console.log(response);
};

var catchErrors = function(err) {
  console.log(err);
};

options.forEach(opt => {
  queueTask()
    .then(logResponse)
    .catch(catchErrors);
})

更新

在评论中,提到了上面的代码片段无法让您知道上一个任务何时完成。这不是原始问题的要求,但是由于一些评论说它可能有用,因此这是您可以使用诺言来实现的一种方法:

var runTasks = new Promise(function(resolve, reject) {

  var queueTask = function(task) {
    // returns a promise
    return queue.add(function() { return rp(task); });
  };

  var logResponse = function(response) {
    console.log(response);
  };

  var catchErrors = function(err) {
    console.log(err);
  };

  options.forEach((opt, i, arr) => {
    
    queueTask()
      .then(logResponse)
      .catch(catchErrors);
    
    if (i === arr.length-1) { resolve(); }
    
  });
  
});

var functionToRunWhenLastTaskCompletes = function() {
  console.log('All tasks are complete.');
};

// runTasks is a promise here, not a function
// so you don't need to call it like a function
runTasks
  .then(functionToRunWhenLastTaskCompletes)

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

在node.js中使用ES6 Promise返回空响应

来自分类Dev

Node.js-在ES6 Promise链中引发异常

来自分类Dev

何时在 Node.js ES6 的 Promise 中启动代码?

来自分类Dev

node.js流中的控制流

来自分类Dev

JS ES6 Promise链接

来自分类Dev

Promise.all中的罐头(ES6和Bluebird)

来自分类Dev

Promise.all在babel ES6实施中解决

来自分类Dev

ES6 Promise.all()对promises数组的奇怪解析

来自分类Dev

使用node.js,流和promise下载文件

来自分类Dev

在Node.js控制器中使用Promise

来自分类Dev

Node.js表达promise.all()。then()不同步

来自分类Dev

Node.js中的Promise.all不调用then函数

来自分类Dev

合并多个控制流的node.js

来自分类Dev

Node.js与Promise并行

来自分类Dev

ES6 Promise.all()错误句柄-是否需要.settle()?

来自分类Dev

使用Promise.all获得基于名称的结果的最佳ES6方法

来自分类Dev

ES6 Promises /在实现多个Promise后调用函数(不能使用Promises.all)

来自分类Dev

如何使用 promise.all 在 ES6/Typescript/Angular 中的多个 if 语句之后返回?

来自分类Dev

MongoDB 表记录没有被 ES6 Promise.ALL 持久化

来自分类Dev

ES6-Promise.resolve中的Promise.all

来自分类Dev

Node.js无法导入ES6模块

来自分类Dev

Node.js导出的行为与ES6模块不同

来自分类Dev

Node.js导入ES6库失败

来自分类Dev

使用ES6的顺序迭代Promise

来自分类Dev

CasperJS / PhantomJS ES6 Promise Polyfill

来自分类Dev

ES6 Promise阻止页面

来自分类Dev

ES6 Promise错误处理

来自分类Dev

在ES6 Promise中链接.then()调用

来自分类Dev

Javascript ES6 Promise 函数选项