【问题标题】:Optimize async call (.then() chaining)优化异步调用(.then() 链接)
【发布时间】:2018-01-12 19:14:06
【问题描述】:

我是异步 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

【问题讨论】:

  • 你可以用Promise.all来做这种事情。
  • 另外,amount * priceArray 没有意义,因为priceArray 是一个数组。
  • @Titus 感谢您指出这一点,我只是更改了代码。

标签: javascript node.js asynchronous promise


【解决方案1】:

您可以使用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));

【讨论】:

  • 这会引发以下错误:(node:6031) UnhandledPromiseRejectionWarning: Unhandled Promise RejectionWarning: Unhandled Promise Rejection (rejection id: 2): TypeError: undefined is not a function
猜你喜欢
  • 2020-07-15
  • 2014-04-11
  • 2020-07-25
  • 2016-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-30
  • 2012-04-16
相关资源
最近更新 更多