How to use the data received from the promise?

  • 0
    DD, don't swear, just tell me or give a link to the article if there is a bookmark where this topic is chewed, here is an example
    let dataUsers;
      let url = "";
        .then((response) => response.json())
        .then((data) => (dataUsers = []));

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

  • 2 Answers
  • 0
    If you want to write in a synchronous style, use async \ await

    const dataUsers = await fetch (url) ...

    If you want to write through promises, then everything should be decided in callbacks, that is, the processing of the result of the api call should occur in the body of then

  • 0
    1) Do not assign the data received in the Promise to a global variable, otherwise you will get poorly maintained shit 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 - mailru / blog / 269465 /
    Conor Chaney

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!