Variable Node.js takes Undefined value

Asked

Viewed 133 times

0

I am trying to pick up the answer of an API, within the function body receives the JSON but outside the function the value is set to Undefined

async function getJSON(){
    var options = {
        url: "https://economia.awesomeapi.com.br/json/all",
        method: 'GET'
    }
    request(options, function(error, response, body){
        console.log(JSON.parse(body))
        return JSON.parse(body)     
    });
};
var cota = getJSON();
console.log(cota)

on the console I have the following exits:

Promise { undefined }

{
  USD: {
    code: 'USD',
    codein: 'BRL',
    name: 'Dólar Comercial',
    high: '5.1951',
    low: '5.101',
    varBid: '0.0953',
    pctChange: '1.87',
    bid: '5.1935',
    ask: '5.1966',
    timestamp: '1585601996',
    create_date: '2020-03-30 18:00:00'
  }...

1 answer

1


You are trying to perform an asynchronous function (async) without waiting for the result, so its console.log is showing a Promise. To wait for the resolution of the promise, you can use the function then:

getJSON().then(console.log);

Or use the clause await within another function async:

(async () => {
  const cota = await getJSON();
  console.log(cota);
})();

Asynchronous functions

The statement async Function defines an asynchronous function, which returns an object Asyncfunction.

You can also define asynchronous functions using a async expression Function.

When an asynchronous function is called, it returns a Promise. When the asynchronous function returns a value, a Promise will be solved with the value returned. When the asynchronous function throws an exception or some value, the Promise will be rejected with the value launched.

An asynchronous function may contain an expression await, which pauses the execution of the asynchronous function and waits for the resolution of the Promise passed, and then resumes the execution of the asynchronous function and returns the solved value.

  • it works now, but how do I export what the quota has stored to another part of the code? I can only use the quota in the console.log

Browser other questions tagged

You are not signed in. Login or sign up in order to post.