【发布时间】:2019-06-09 04:03:22
【问题描述】:
我正在发出 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 的情况下做到这一点?
【问题讨论】:
-
承诺只能被解决一次。这是一个一次性设备。它从待处理变为已解决或待处理变为被拒绝,之后永远不会改变。此外,您的代码没有显示您如何将其包装在
new Promise()中,也没有显示您想如何使用它来了解建议的内容。 -
我刚刚更新了它,如果有其他方法可以做到这一点,将不胜感激!如果需要,我会提供更多额外信息。
-
你真正想解决什么问题?您已经将
.onreadystatechange作为事件处理程序,每次状态更改都会调用它。对于打算多次触发的东西,Promise 不是合适的工具。也许一个 eventEmitter 或一个简单的回调是正确的工具。
标签: javascript ajax promise es6-promise