簡體   English   中英

Node.js中的承諾和數組

[英]Promises and arrays in Node.js

我正在使用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等待一系列的諾言完成。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM