R
R
reinmaker902020-11-15 14:02:12
JavaScript
reinmaker90, 2020-11-15 14:02:12

How to use data received from promise?

DD, please don’t swear, but just tell me or give a link to the article if there are bookmarks where they chew on this topic, here is such an example

let dataUsers;
  let url = "https://jsonplaceholder.typicode.com/users";
  fetch(url)
    .then((response) => response.json())
    .then((data) => (dataUsers = [...data]));

How can you later use the data stored in the dataUsers variable in the code?, i.e. if you call it right away, it is obvious that it will return undefined, if done through setTimeout, then I can get the values, but this is definitely not true, as when receiving data from an asynchronous query then use them in synchronous?
And if someone knows why the same construction works in vue.js, i.e. I can make a request from the method and write the result to data and then use it

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Arthur, 2020-11-15
@cloudz

If you want to write in the style of synchronous code, use async\await
const dataUsers = await fetch(url)...

V
Vladimir, 2020-11-15
@Casufi

1) Do not assign the data received in the Promise to a global variable, otherwise you will get badly maintained shitty code.
2) Move the code that uses dataUsers into a separate function and call it in then
This was the first stage, the second stage - https://habr.com/ru/company/mailru/blog/269465/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question