【问题标题】:Using promise to GET over XHR returns pending promise使用 Promise 通过 XHR GET 返回待处理的 Promise
【发布时间】: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


    【解决方案1】:

    这也是预期的行为。 您了解异步代码的行为方式吗?

    console.log(newResult) 在此之前运行:

    var newResult = initRequest('/outfits/outfitList')
        .then(function (result) {
            console.log(result)
            resolve(result);
        })
        .catch(function () {
            console.log('err')
        });
    

    您应该在.then() 回调中处理您的结果:

      var newResult = initRequest('/outfits/outfitList')
        .then(function (result) {
            // Do your stuff with results here
    
        })
        .catch(function () {
            console.log('err')
        });
    

    如果您觉得阅读困难,可以尝试使用async/await 代替

    var result = await initRequest('/outfits/outfitList')
    console.log(result)
    

    【讨论】:

      【解决方案2】:

      我认为您的代码缺少reject 状态,可能您的请求未按预期完成。试试这个改进的代码:

      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);
                          reject(xhr.statusText);
                      }
                  } else {
                      reject(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');
              reject('error in request');
          });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-04
        • 1970-01-01
        • 1970-01-01
        • 2019-02-13
        • 2018-08-01
        • 2021-02-20
        • 2016-08-01
        相关资源
        最近更新 更多