1

I am trying to use the variable bida elsewhere in my code. For example, when I try to create the variable mida. Is there a way to do that without nesting everything inside the getFX() function? I understand it's an async function issue but how can I get around it?

const fetch = require("node-fetch");

async function getFX() {

let bida;

  try {

    var req = await fetch('https://economia.awesomeapi.com.br/all/USD-BRL');
    var response = await req.json()


   bida = await response.USD.bid;
   aska = await response.USD.ask;

    console.log(bida, aska)

  } catch (e) {
    // handle error
    console.error(e)
  }
}

getFX()

var mida = bida + 1;

console.log (mida);
Daniel_Knights
  • 7,940
  • 4
  • 21
  • 49
MarceloFla
  • 13
  • 1
  • 3
  • Only if you `await getFX()` or use it in a `getFX().then(...)`. Otherwise, no. That's the purpose of async functions, other code can run while the async task is being completed. So without `awaiting` it, `bida` will be `undefined` – blex Jun 20 '20 at 15:35
  • what do you mean by without nesting? you can use a callback or you have to return a promise and await for getFX() – Zohaib Sohail Jun 20 '20 at 15:35
  • Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – ponury-kostek Sep 14 '20 at 18:27

1 Answers1

5

you should initialize the bida variable outside of the getFX() function to be able to access it elsewhere in that file, and also set the value of mira variable only when getFX resolves using .then() to be able to use the value of bida because getFX is an async function. Here is how I did it:

const fetch = require("node-fetch");

let bida;

async function getFX() {


    try {

       var req = await fetch('https://economia.awesomeapi.com.br/all/USD-BRL');
       var response = await req.json()


       bida = await response.USD.bid;
       aska = await response.USD.ask;

       console.log(bida, aska)

    } catch (e) {
        // handle error
        console.error(e)
    }
}


getFX().then(() => {
    var mida = bida + 1;
    console.log (mida);
})

Hope it helps !

Achraf Ghellach
  • 1,706
  • 1
  • 8
  • 6