Я делаю javascript-запрос AJAX, если я использую классический callback
, я могу вызвать обратный вызов функции onreadystatechange
, и он возвращает все значение readyState
.
Я попытался изменить мои callback
функции на обещания. Когда я разрешил функцию 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
?