0

I have this method, which has an IF statement and returns this.status.

Here is the code:

myMethod() {
        return new Promise(resolve => {
            let httpRequest = new XMLHttpRequest();
            httpRequest.open("GET", "http://someurl.com", true);
            httpRequest.send();
            httpRequest.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    // I need this.status to be able to use outside here
                }
            };

            resolve();

        })
    }

How can I get this.status result outside the if() {} area so I can pass it to other methods?

  • 4
    You don't; you `resolve()` _inside_ the if. – tkausl Sep 13 '18 at 12:33
  • 5
    Why are you resolving BEFORE the Ajax call is done??? You basically ordered a pizza and as soon as you finish ordering, you are trying to eat the pizza. You did not wait for it to be made and delivered. `if (this.readyState == 4 && this.status == 200) { resolve(this) }` – epascarello Sep 13 '18 at 12:35
  • I suggest you read the documentation on Promises, I think you are missing the purpose there. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise – Seblor Sep 13 '18 at 12:36

3 Answers3

0

to save this.status result outside the if() {} area, you just need to declare a variable out of the area, and assign {this.status result} to it. for example, you declare global variable out of myMethod(), and set its value using this.status.

to pass it to other methods, you should use similar logic, define a method out of myMethod(), in if() area, you just call it and pass this.status as a parameter.

to remind you, to handle this kind of 'call back', you need to think of a better way of handling errors and showing up error messages to end users.

Hope it helps.

Victor Xie
  • 148
  • 1
  • 9
0

You can resolve the httpRequest after the response is sent.

myMethod() {
    return new Promise(resolve => {
        let httpRequest = new XMLHttpRequest();
        httpRequest.open("GET", "http://someurl.com", true);
        httpRequest.send();
        httpRequest.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                resolve(this);
            }
        };
    })

Then you could access the httpRequest object with:

myMethod().then(response =>
    console.log(response);
    //response.status = 200;
);
Sven Eberth
  • 3,057
  • 12
  • 24
  • 29
rnarcos
  • 86
  • 1
  • 2
  • 12
-1

Create an variable after XmlHttpRequest declaration if:

let requestStatus;

And after if statement assign it with the this.status:

requestStatus = this.status;
Sven Eberth
  • 3,057
  • 12
  • 24
  • 29