B
B
Balera2019-07-04 18:43:39
JavaScript
Balera, 2019-07-04 18:43:39

Promis is it necessary for the function code to wait until setTimeout works and go no further?

here is the code you need so that you
don’t go out it came out only after the function above

function httpGet(url) {
      return new Promise(function (resolve, reject) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.onload = function () {
          if (this.status == 200) {
            resolve(this.response);
          } else {
            var error = new Error(this.statusText);
            error.code = this.status;
            reject(error);
          }
        };
        xhr.onerror = function () {
          reject(new Error("Network Error"));
        };
        xhr.send();
      });
    }
    httpGet("/article/promise/user.json")
      .then(
        response => console.log(`Fulfilled: ${response}`),
        error => console.log(`Rejected: ${error}`)
      );
    console.log('не лезь');

don't bother printing 1 but it should be the last

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
kova1ev, 2019-07-04
@Balera

A promise is executed asynchronously, that is, it does not block the flow of program execution, and this is what it is for. The interpreter starts executing the promise and at the same time continues to execute the main thread of the program, that is, in this case it prints "don't bother" to the console. All code that should be executed only after the promise is fulfilled will have to be pushed into the promise callback. Alternatively, use async await to make it more readable.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question