0

I want to make a async Function work in parallel for the .map loop.

Also when I call it like below I get ‘Promise ’ eg

console.log(getExchangeRate(variable));

Hey I am trying to run a Async function in NodeJS where inside it does some calculations in parallel.

const getExchangeRate = async (orderBaseCurrency) => {
  try {

    const exchangeRate = await axios.get(`http://api.example.com`);
    const data = exchangeRate.data.data.rates;

    const usd = data.usd;
    const aud = data.aud;

    // loop through above with the calc below in parallel 
    const decimalEntry = new Decimal(1);
    const answer = new Decimal(decimalEntry.times(orderAmount).toFixed(18, Decimal.ROUND_HALF_UP));
    return answer.toPrecision();
    //^^ loop

      } catch (error) {
    console.error(error);
    console.log(error);
      }
    }
Trent
  • 141
  • 9
  • If the function is `async` you need to `await` it. – deceze May 02 '18 at 07:06
  • How do you mean? I used it in the first request eg exchangeRate. – Trent May 02 '18 at 07:24
  • Yeah, because you're `await`ing an asynchronous function within `getExchangeRate`, that makes `getExchangeRate` an `async`hronous function as well by necessity. In fact, you have annotated it as such. So you need to `await getExchangeRate` as well. It can't suddenly become synchronous. – deceze May 02 '18 at 07:27
  • I’m a little confused. I realise I need to await the exchangeRate. But how do I await the getExchangeRate function? Thanks – Trent May 02 '18 at 07:29
  • The same way you `await axios.get`. `await getExchangeRate(variable)`. – deceze May 02 '18 at 07:30
  • But you can’t use await outside of the async function? – Trent May 02 '18 at 07:32
  • Yeah, any function `await`ing a function must itself also be `async`, that's the way it goes. Alternatively use the returned promise and add a `.then` callback. That's the same thing using different notation. – deceze May 02 '18 at 07:34
  • Ah ok. Is that cause the function itself returns a promise? How come just calling the function normally below it is ok but not when exporting it. Also can you confirm if I have declared the function correctly to run in parallel? Cheers – Trent May 02 '18 at 08:13

0 Answers0