使用promise构建对象数组的正确方法然后发送到客户端 - nodejs express

时间:2017-05-16 06:45:30

标签: javascript node.js promise

我试图建立一个对象数组并将其发送给客户端。问题是发送的数组是空白的,因为异步代码(或者我正在学习)。

我想循环构建数组,然后从服务器向客户端发送响应。我被告知承诺是这里做到这一点的最佳方式,但我无法理解如何实施。诺言如何看待这里?



var rates = [];
for (var i = 0, len = cryptoxArray.length; i < len; i++) {

  cryptoxArray[i].getRate({
    pair: "XBT_USD"
  }, function(err, rateResponse) {
    if (!err)
      rates.push(rateResponse);
  });

  //I want this last part to wait until the array has been built so 
  //the array is '[object][object]'

  console.log('rates: ' + rates); // now is outputting 'rates: []'
  return res.json(rates);
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

正如您指定的承诺

Promise.all(cryptoxArray.map(function (cryptox) {
  return new Promise(function (resolve, reject) {
    return cryptox.getRate({ pair: "XBT_USD" }, function (err, rateResponse) {
      return err ? reject(err) : resolve(rateResponse);
    });
  });
})).then(function (rates) {
  return res.json(rates);
});

或在超ES2015中

Promise.all(cryptoxArray.map(cryptox =>
    new Promise((resolve, reject) =>
        cryptox.getRate({ pair: "XBT_USD" }, (err, rateResponse) => 
            err ? reject(err) : resolve(rateResponse)
        )
    )
))
.then(rates=> res.json(rates));