Home Optimize async call (.then() chaining)
Reply: 1

Optimize async call (.then() chaining)

mrks
1#
mrks Published in 2018-01-12 09:48:34Z

I'm new to asynchronous javascript code and want to use it more and more in my current node.js project (express.js api).

I have this function for my GET route, it works but it is obviously not the correct way to do it:

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

The function ccHelper.coinInUSD calls this (for reference is needed):

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

Can someone explain me how to avoid this chaining and what the correct pattern would be? I did this because I can only set res.json once.

Titus
2#
Titus Reply to 2018-01-12 11:14:06Z

You could use Promise.all for this kind of thing.

Here is an example:

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));
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.364343 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO