【发布时间】:2018-12-31 12:42:55
【问题描述】:
我正在尝试使用 Promise 通过 XHR 发出异步请求。我可以从 .then 内部控制台记录我的结果,但在外部它返回待处理。
function initRequest(url) {
return new Promise(function(resolve, reject) {
xhr.open("GET", url, true);
xhr.onload = function(e) {
// check if XHR transaction is complete
if (xhr.readyState === 4) {
// if it is, do the things
if (xhr.status === 200) {
// Parse outfitList
responseText = JSON.parse(xhr.response)
resolve(this.responseText);
// Print outfitList to cards
var div = document.getElementById('outfitCards');
//return outfitList;
// If it can't, do an error
} else {
console.error(xhr.statusText);
}
}
};
xhr.setRequestHeader("Content-type", "x-www-form-urlencoded");
xhr.send();
});
}
var newResult = initRequest('/outfits/outfitList')
.then(function(result) {
console.log(result)
resolve(result);
})
.catch(function() {
console.log('err')
});
console.log(newResult);
result 是一个数组,当我使用 console.log(result) 时它看起来很好。 console.log(newResult) 然而,返回一个未决的承诺。
【问题讨论】:
标签: javascript node.js promise xmlhttprequest