Since your code is asynchronous, to ensure that the value of the variable is populated you must do it within the then
. Currently there is the option of using the async/await
also ensures that the code that executes an asynchronous function waits for its execution before continuing. However, the instruction await
(described above) can only be used in one function with instruction async
, which determines that it is "asynchronous" and will return a promise. Therefore your code can be translated into:
const buscar = async() => {
try {
const response = await fetch('https://api.myjson.com/bins/dhhvz');
const r = response.json();
console.log(r);
} catch (e) {
console.error(e);
}
};
buscar();
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.
The assignment should work normally. The only detail you need to take care of is not to use the variable before the request is completed. The idea is that by being asynchronous, you do what you need to do with JSON itself
then
. Why you need to assign to the variable?– Woss
You want to assign Response to the dia_do_mes variable?
– Daniel Mendes