简体   繁体   English

如何在readystatechange上承诺AJAX请求?

[英]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. 我正在发出javascript AJAX请求,如果使用的是经典callback ,则可以在onreadystatechange函数上调用该回调,并返回所有readyState值。

I tried changing my callback functions to promises. 我尝试将callback函数更改为promise。 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. 当我解析onreadystatechange函数时,我注意到它仅返回第一个readyState值,即2,而不是2,3和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. 我希望它返回所有readyState值。 If my approach won't work, is there any possible way to do this without using callback ? 如果我的方法行不通,有没有不使用callback

So you want to listen/fetch value from multiple event which is generated by onreadystatechange method. 因此,您想从onreadystatechange方法生成的多个事件中监听/获取值。 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. 您可以从rxjs库使用observable,也可以在nodejs中使用事件监听器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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