javascript - Node.js 中的 Promise 和数组

标签 javascript arrays node.js foreach promise

我正在使用 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();
});

最佳答案

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

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);
}

关于javascript - Node.js 中的 Promise 和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31838843/

相关文章:

javascript - react-native-modalbox 卡在子组件上下文中

javascript - 通过ID更改标签背景颜色

Javascript 在单个浏览器中打开多个选项卡

python - 如何使用 numpy 按季度分组并计算数组的平均值?

javascript - Nodejs Promise 序列的问题

node.js - 用于 Node 在非断点处停止的 WebStorm 调试器

node.js - Mocha 测试突然停止,出现 : Cannot find module 'pg-native'

javascript - 用正则表达式删除子字符串

javascript - 如何使用 jquery 访问 JSON 嵌套数组

java - 将 int 数组转换为 char 数组