2

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);
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 Commented Jun 20, 2020 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() Commented Jun 20, 2020 at 15:35
  • Does this answer your question? Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference Commented Sep 14, 2020 at 18:27

1 Answer 1

7

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 !

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.