简体   繁体   中英

I don't understand Ajax, Promise and XMLHttpRequest

this is my code:

const getXHR = (type, url) => {

  let xhr = new XMLHttpRequest();

  let p = new Promise(function(resolve, reject) {

    xhr.onload = function() {
        if(xhr.status >= 200 && xhr.status < 400) {
            resolve(xhr.responseText);
        } else {
            reject(new Error(`Error. Code ${xhr.status}`))
        }
    };

    xhr.onerror = function() {
        reject(new Error(`Error. Problem with connection`));
    }

});

xhr.open(type, url);

return {xhr, p};

};

export default {

get(url) {

  var _getXHR = getXHR('GET', url),
      xhr = _getXHR.xhr,
      p = _getXHR.p;

    xhr.send();

    return p;

  }
}

I don't understand why I have to use this code to get it to work:

var _getXHR = getXHR('GET', url),
      xhr = _getXHR.xhr,
      p = _getXHR.p;

instead of this:

var xhr = getXHR('GET', url).xhr,
    p = getXHR('GET', url).p;

What is wrong with this? For me it is excatly the same lines of code. I would be grateful for any kind of help. Maybe someone has a link where I can find the answer?

Thank You

var xhr = getXHR('GET', url).xhr,
p = getXHR('GET', url).p;

Creates two requests, and then gets the xhr object of the first, and the promise of the second. The xhr request of the first is sent , that one of the promise is always in a pending state. So thats probably not working. May use some destructuring:

var { p, xhr } = getXHR('GET', url);
xhr.send();
return p;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM