首页 > 解决方案 > 异步与标准回调混合

问题描述

我刚刚开始Promise在 Javascript 中学习 s,并且偶然发现了async/await.

据我了解,如果我指定一个函数,则asyncjavascript 将始终包装我函数的内容并返回 aPromise而不是我返回的任何内容。

让我们假设以下场景:

async function httpRequest() {
   oReq = new XMLHttpRequest();
   oReq.addEventListener("load", function() {
      return this.responseText;
   });

   oReq.open("GET", "http://some.url.here");
   oReq.send();
}

httpRequest().then(function(httpResult) {
    console.log(httpResult);
}); 

我是否正确假设上述情况不起作用,因为httpRequest()没有返回任何东西,回调XMLHttpRequest只返回一些东西,因此我的结果很可能是undefined

如果是,我将如何修复httpRequest()它以便在某个async/await场景中工作?

标签: javascriptasync-awaites6-promise

解决方案


您在这里拥有的是一个执行异步操作的异步函数,其中该操作不使用承诺。这意味着您需要设置一个函数来显式地管理和返回一个 Promise。您不需要async此处的关键字,因为您想显式地创建您创建return的 a Promise,而不是 async 关键字为您创建的承诺(您无法直接管理)。

function httpRequest() {

   // Return a promise (this is what an async function does for you)
   return new Promise(resolve => {
     const oReq = new XMLHttpRequest();
     oReq.addEventListener("load", function() {

        // Resolve the promise when the async operation is complete.
        resolve(this.responseText);
     });

     oReq.open("GET", "http://some.url.here");
     oReq.send();
   };
}

现在该函数显式返回了一个 Promise,它可以awaitasync函数一样被编辑。或与then()任何承诺一样使用。

async function someFunction() {
  // await
  const awaitedResponse = await httpRequest();
  console.log(awaitedResponse);

  // or promise chain
  httpRequest().then(responseText => console.log(responseText));
};

推荐阅读