[英]How can I promisify an AJAX request onreadystatechange?
我正在發出javascript AJAX請求,如果使用的是經典callback
,則可以在onreadystatechange
函數上調用該回調,並返回所有readyState
值。
我嘗試將callback
函數更改為promise。 當我解析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
});
我希望它返回所有readyState
值。 如果我的方法行不通,有沒有不使用callback
?
因此,您想從onreadystatechange方法生成的多個事件中監聽/獲取值。 對於這個承諾不是很有幫助。 如果您想從多個事件中獲取價值。 您可以從rxjs庫使用observable,也可以在nodejs中使用事件監聽器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.