【问题标题】:Promises and arrays in Node.jsNode.js 中的 Promise 和数组
【发布时间】:2015-10-28 14:28:27
【问题描述】:

我正在使用 Bluebird 并请求 npm 包:

var Promise = require('bluebird');
var request = Promise.promisify(require('request'));
Promise.promisifyAll(request);

我有一个输出到 REST 端点并返回一些数据的函数:

var getData = function() {
    options.url = 'http://my/endpoint';
    options.method = 'GET'; //etc etc...
    return request(options);
};

getData().then(function(response) {
  console.log(response); //-> this returns an array
});

response 是一个由 REST 端点返回的数组。问题是现在我想对数组中的每个项目进行第二次请求,例如:

var getIndividualData = function(data) {
  data.forEach(function(d) {
    options.url = 'http://my/endpoint/d'; //make individual requests for each item
    return request(options);
  });
};

上述当然不起作用,我明白为什么。但是,我不明白如何才能使这项工作。理想情况下,我想要的是一条链,例如:

getData().then(function(response) {
  return getIndividualData(response);
}).then(function(moreResponse) {
  console.log(moreResponse); // the result of the individual calls produced by getIndividualData();
});

【问题讨论】:

    标签: javascript arrays node.js foreach promise


    【解决方案1】:

    您可以使用Promise.all 等待一系列承诺完成。

    getData()
      .then(getIndividualData)
      .then(function(moreResponse) {
        // the result of the individual calls produced by getIndividualData();
        console.log(moreResponse);
       });
    
    function getIndividualData(list) {
      var tasks = list.map(function(item) {
        options.url = // etc.
        return request(options);
      });
    
      return Promise.all(tasks);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-16
      • 2016-10-09
      • 1970-01-01
      • 2022-01-10
      • 2017-06-28
      • 2019-01-12
      • 1970-01-01
      • 2011-05-16
      相关资源
      最近更新 更多