Javascript 为什么承诺返回空字符串?
我有一个函数foo,它发出Ajax请求。 我尝试从回调返回数据,并成功地获得了带有“xhr.onload”的数据,但得到了带有“xhr.onreadystatechange”的空字符串(“”) 谁能告诉我为什么 多谢各位Javascript 为什么承诺返回空字符串?,javascript,asynchronous,promise,Javascript,Asynchronous,Promise,我有一个函数foo,它发出Ajax请求。 我尝试从回调返回数据,并成功地获得了带有“xhr.onload”的数据,但得到了带有“xhr.onreadystatechange”的空字符串(“”) 谁能告诉我为什么 多谢各位 function foo(url){ return new Promise(function(resolve,reject){ var xhr = new XMLHttpRequest(); xhr.open("GET",url,true); // xh
function foo(url){
return new Promise(function(resolve,reject){
var xhr = new XMLHttpRequest();
xhr.open("GET",url,true);
// xhr.onload = function(){
// if(xhr.status == 200){
// resolve(xhr.responseText);
// }else{
// reject("false")
// }
// }
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState && xhr.status == 200){
resolve(xhr.responseText);
}else{
reject("false")
}
}
})
}
foo(url).then(function (data){
console.log(data)
},function (err){
console.log(err)
})
您的
onreadystatechange
处理程序不正确。您需要检查readyState
中的值4(不仅仅是任何真实值),并且在readyState
为4之前,您不希望拒绝:
if(xhr.readyState === 4){
if (xhr.status == 200) { // or xhr.status >= 200 && xhr.status < 300
resolve(xhr.responseText);
} else {
reject("false")
}
}
if(xhr.readyState==4){
如果(xhr.status==200){//或xhr.status>=200&&xhr.status<300
解析(xhr.responseText);
}否则{
拒绝(“假”)
}
}
但对于现代浏览器,您可能会使用它,这已经提供了一个承诺。只是要确保不要发表(这是我贫血小博客上的一篇文章)
至于你为什么看到你所看到的,因为你在附加处理程序之前调用了
open
和send
,显然你没有得到readyState
1(opened)的回调,所以看起来你得到的第一个回调是在收到头的时候(readyState
2),此时将设置xhr.status
,因此您正在解决您的承诺,但当然,请求主体尚未收到。感谢您的帮助!