简体   繁体   中英

How can I promisify an AJAX request onreadystatechange?

I'm making a javascript AJAX request, if I am using the classic callback , I am able to to call the callback on the onreadystatechange function and it's returning all the readyState value.

I tried changing my callback functions to promises. When I resolved on the onreadystatechange function, I notice it's only returned the first readyState value which is 2, instead of 2,3 and 4.

_.request = async (headers, path, method, queryObj, payload) => {
  return new Promise((resolve, reject) => {
    path =  (typeof path == 'string') ? path : '/';
    queryObj =  (typeof queryObj == 'object' && queryObj !== null) ? queryObj : {};
    method = (typeof method == 'string' && ['POST','PUT','DELETE','GET'].indexOf(method.toUpperCase()) > -1) ? method.toUpperCase() : 'GET';
    headers = (typeof headers == 'object' && headers !== null) ? headers : {};
    payload = (typeof payload == 'object' && payload !== null) ? payload : {};

    let requestUrl = path + '?';
    let counter = 0;
    for (let i in queryObj) {
      if (queryObj.hasOwnProperty(i)) {
        counter++
        if (counter > 1) {
          requestUrl += '&';
        }
        requestUrl += i + '=' + queryObj[i];
      }
    }
    const xhr = new XMLHttpRequest();
    xhr.open(method, requestUrl, true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    for (let i in headers) {
      if (headers.hasOwnProperty(i)) {
        xhr.setRequestHeader(i, headers[i]);
      }
    }
    xhr.send(JSON.stringify(payload));
    xhr.onreadystatechange = () => {
      const response = {
        rs: xhr.readyState,
        sc: xhr.status,
        re: xhr.responseText
      };
      try {
        response.re = JSON.parse(response.re);
        resolve(response);
      } catch {
        resolve(response);
      }
    }
  });
}

$(document).on('ready', async (e) => {
  const data = await _.request(undefined, '/views/getarticle', 'get', undefined, undefined);
  console.log(data); // readyState: 2
});

I expected it returned all the readyState values. If my approach won't work, is there any possible way to do this without using callback ?

So you want to listen/fetch value from multiple event which is generated by onreadystatechange method. For this promise is not very helpfull. if you want to get value from multiple event. you can use observable from rxjs library or you can use event listener in nodejs.

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