使用承诺通过XHR获取GET返回未完成的承诺

时间:2018-12-31 12:42:56

标签: javascript node.js promise xmlhttprequest

我正在尝试使用Promise通过XHR发出异步请求。我可以从.then内部console.log我的结果,但是在外部则返回待处理状态。

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)但是会​​返回未完成的承诺。

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

我认为您的代码缺少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');
    });