代码之家  ›  专栏  ›  技术社区  ›  Sylvia

为什么承诺返回空字符串?

  •  -1
  • Sylvia  · 技术社区  · 7 年前

    我有一个函数foo,它发出Ajax请求。

    有人能告诉我为什么吗??

    非常感谢你!

    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)
    })
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   T.J. Crowder    7 年前

    你的 onreadystatechange 处理程序不正确。你需要检查一下 readyState 对于值4(不仅仅是任何真实值),您不想拒绝直到 重新启动状态

      if(xhr.readyState === 4){
          if (xhr.status == 200) { // or xhr.status >= 200 && xhr.status < 300
              resolve(xhr.responseText);
          } else {
              reject("false")
          }
      }
    

    但在现代浏览器中,您可能会使用 fetch 相反,这已经提供了一个承诺。只是要确保不要 these common mistakes (这是我贫血小博客上的一篇文章)。

    既然你打电话来,你为什么要看到你看到的东西 open send 在附加处理程序之前,显然您没有收到 重新启动状态 1(已打开),因此您收到的第一个回调似乎是在收到标头时( 重新启动状态 2) ,此时 xhr.status