优化异步调用(.then()链接)

时间:2018-01-12 09:48:35

标签: javascript node.js asynchronous promise

我是异步javascript代码的新手,想在我当前的node.js项目(express.js api)中越来越多地使用它。

我的GET路线有这个功能,它有效,但显然不是正确的方法:

portfolio: function(req, res, next) {
  const ethCoins = 0.001;
  const ltcCoins = 0.789;
  const xrpCoins = 0.987;
  const xrbCoins = 0.123;
  const btcCoins = 0.321;
  let ethSum, btcSum, ltcSum, xrpSum, xrbSum, cryptoSum;

  let ethValue = ccHelper.coinInUSD('ETH', ethCoins);
  let ltcValue = ccHelper.coinInUSD('LTC', ltcCoins);
  let xrpValue = ccHelper.coinInUSD('XRP', xrpCoins);
  let xrbValue = ccHelper.coinInUSD('XRB', xrbCoins);
  let btcValue = ccHelper.coinInUSD('BTC', btcCoins);

  ethValue.then(result => {
    ethSum = result;
    ltcValue.then(result => {
      ltcSum = result;
      xrpValue.then(result => {
        xrpSum = result;
        xrbValue.then(result => {
          xrbSum = result;
          btcValue.then(result => {
            btcSum = result;
            let coinSum = ethSum + ltcSum + xrpSum + xrbSum + btcSum;
            res.json(coinSum);
          })
        })
      })
    })
  })
},

ccHelper.coinInUSD函数调用它(需要参考):

coinInUSD: function(crypto, amount){
  return cc.price(crypto, 'USD')
    .then(prices => {
      const priceArray = [];
      Object.keys(prices).forEach((key) => {
        priceArray.push(prices[key]);
      });
      let priceSum = priceArray.reduce((a, v) => (a+v), 0);
      const currentValue = amount * priceSum;
      return currentValue;
  }).catch(console.error)
},

有人可以解释我如何避免这种链接以及正确的模式是什么?我这样做是因为我只能设置res.json一次。

1 个答案:

答案 0 :(得分:3)

你可以使用Promise.all来做这件事。

以下是一个例子:

const ethCoins = 0.001;
const ltcCoins = 0.789;
const xrpCoins = 0.987;
const xrbCoins = 0.123;
const btcCoins = 0.321;

let ethValue = ccHelper.coinInUSD('ETH', ethCoins);
let ltcValue = ccHelper.coinInUSD('LTC', ltcCoins);
let xrpValue = ccHelper.coinInUSD('XRP', xrpCoins);
let xrbValue = ccHelper.coinInUSD('XRB', xrbCoins);
let btcValue = ccHelper.coinInUSD('BTC', btcCoins);

Promise.all([ethValue, ltcValue, xrpValue, xrbValue, btcValue]).then(values => {
     let coinSum = values.reduce((a, v) => (a+v), 0);
     res.json(coinSum);
}).catch(e => console.error(e));