How to assign Fetch value to a variable

Asked

Viewed 903 times

5

I have the following code below

 dia_do_mes = {};

  fetch('https://api.myjson.com/bins/dhhvz')
  .then(response => {
    return response.json()
  })
  .then(r => {
    console.log(r)
  })
  .catch(err => {
    // Do something for an error here
  })

My only question is, how do I assign the answer in JSON na no 'r', type by log console I see the object returning correctly, but when I try assigns the 'r' to variable dia_do_mes = {};, it doesn’t work, someone can help me?

  • 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?

  • You want to assign Response to the dia_do_mes variable?

3 answers

5

I don’t know if I understood your question correctly, but the return is an object, with several other objects inside, so in the variable dia_do_mes doesn’t need the {}, just assign the value of r a dia_do_mes, tbm I advise you to put dia_do_mes in a variable or constant:

let dia_do_mes;

  fetch('https://api.myjson.com/bins/dhhvz')
  .then(response => {
    return response.json()
  })
  .then(r => {
    dia_do_mes = r;
    console.log(dia_do_mes)
  })
  .catch(err => {
    // Do something for an error here
  })

4


Thiago, when you work with requests, usually they have asynchronous behavior, because of that you can not perform this direct assignment.

An option would be to work with async/await, it would also be possible to assign the value only in the return then of variable r, among other possibilities:

// Exemplo com async/await
let dia_do_mes = {};

(async () => {
    dia_do_mes = await fetch('https://api.myjson.com/bins/dhhvz')
        .then(response => {
        return response.json();
        })
        .then(r => {
             return r;
        })
        .catch(err => {
            // Do something for an error here
        });
    console.log("Exemplo com async/await", dia_do_mes);
})();

// Exemplo pegando o valor no bloco then do retorno r
let outro_dia_do_mes = {};

fetch('https://api.myjson.com/bins/dhhvz')
    .then(response => {
        return response.json();
    })
    .then(r => {
         outro_dia_do_mes = r;
         console.log("Exemplo no bloco do then", outro_dia_do_mes);
    })
    .catch(err => {
        // Do something for an error here
    });

2

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.

Browser other questions tagged

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