当前位置: 首页 > 知识库问答 >
问题:

使用promise获得XHR将返回挂起的promise

隗轶
2023-03-14

我试图使用promise通过XHR发出异步请求。我可以从内部将结果记录到console.log中,然后在外部返回pending。

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)时,它看起来很好<但是,code>console.log(newResult)返回一个挂起的promise。

共有2个答案

林德惠
2023-03-14

我认为您的代码缺少拒绝状态,也许您的请求没有按预期完成。试试这个改进的代码:

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');
    });
华聪
2023-03-14

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

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

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

你应该在中处理你的结果。然后()回调:

  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)
 类似资料:
  • 我正在努力理解如何在Javascript中获得一个承诺的值,以便能够检查它是真的还是假的。 如果我console.log有效变量,它将返回以下内容: 在我的if语句中,我试图检查允诺值是否为真,但我不知道如何访问该值:/谁能告诉我如何检查该值吗? 谢谢

  • 如果用非空数组调用promise.all或promise.race,它们将返回一个挂起的promise: 为什么promise。所有功能都是这样设计的?似乎没有很好的理由不一致,但也许我错过了什么。

  • 我有以下几门课 我想为viewModel和UseCase编写一个ermetic测试: 但ViewModel.car似乎总是为空。在测试体中mockapi.fetchcar()检索提供的值,但在FetchCarUseCase中不检索。此外,如果我从界面中移除suspend关键字,那么嘲弄似乎可以很好地工作。 目前,由于一些其他条件,我无法使用Mockk库,所以我只能使用mockito。 我是不是漏掉

  • 问题内容: 我想使用这样的Promise来调用Google Maps Geocoding API: 当我调用函数请求时,我发现我得到了一个Promise而不是一个值: 为什么不答应。然后在返回值之前执行?我如何从这个承诺而不是另一个承诺中获得价值? 问题答案: 如果您依赖承诺来返回数据,则必须从函数中返回承诺。 一旦调用堆栈中的1个函数异步,那么要继续线性执行,所有要调用它的函数也必须异步。(异步

  • 我正在尝试用Async/Await进行一些动态数据建模。我有两个endpoint,第一个将返回对象数组。数组中的这些实体具有从另一个endpoint获取的子实体。 所以我试图实现的结果类似于: 这就是我试图解决这个问题的方法: 我所期待的: 我得到的是: 我不知何故监督了我的承诺.所有链,所以我只是在我的数据对象中获得解析的承诺,有没有关于如何在其中获得普通数据的提示?或者如何将一个数组解析的承诺

  • 问题内容: 我有python背景,目前正在迁移到node.js。由于其异步特性,我无法适应node.js。 例如,我试图从MySQL函数返回一个值。 经过一番阅读后,我意识到上面的代码无法正常工作,由于node.js的异步特性,我需要返回一个promise。我无法编写像python这样的node.js代码。如何转换为返回承诺,以及如何处理返回的值? 实际上,我想做的就是这样。 如何以可读的方式在n