就返回值而言,异步函数中的await 关键字有什么意义?

vrs*_*ion 3 javascript asynchronous async-await

我研究了很多帖子、文章和文档。我正在寻求更深入的理解。

来自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

await表达式导致async函数执行暂停,直到 aPromise确定,[...]

let fetchLocation = () => {
  //fetches information from satellite system and 
  //returns a Vector2 of lat long on earth
  return new Promise(resolve => {
    setTimeout(() => {
      resolve({
        lat: 73,
        long: -24
      });
    }, 2000);
  });
}

//async functions automatically return a promise.
let main = async() => {

  //awaits the promises resolution
  let result = await fetchLocation();
  console.log("I'm the awaited promise result", result)

  //immediately returns a promise as promise pending 
  return result;
}

console.log(main().then(res => console.log("I'm the original promise, just passed along by the async function, it didn 't a-wait for me", res)))
Run Code Online (Sandbox Code Playgroud)

在深入这个兔子洞之前,我知道 async/await 是使异步代码看起来同步的语法糖。

因此,我完全希望看到 main 返回经纬度坐标。相反,它返回一个承诺。

有几个问题。

  1. MDN文档有错吗?它实际上没有暂停执行吗?看来await关键字实际上并没有“暂停”函数执行......调用main立即返回一个Promise<pending>对象。然而,在它返回后,我们在 waited 变量中收到已履行承诺的值result。我想这来自事件循环?(异步返回语句仍然是同步的。)

  2. 所以看起来await 解开了一个promise,async 包装了一个promise,但是你需要在async 中使用await。我知道await实际上可能是promise.then(),但如果他们想让它在外观上完全同步,为什么不让async函数在与await一起使用时返回已解析的promise值呢?否则 async wait 似乎有点多余。

Que*_*tin 5

\n

MDN文档有错吗?

\n
\n

\n
\n

它实际上没有暂停执行吗?

\n
\n

它暂停函数的执行async,将 Promise 交还给调用函数 \xe2\x80\x94,因为它还没有到达函数中async它知道返回什么内容的点 \xe2\x80\x94 然后执行调用函数(以及其余代码)继续。

\n
\n

然而,在它返回后,我们在等待的变量结果中收到已履行承诺的值。我想这来自事件循环?

\n
\n

async当事件循环停止忙碌时(运行首先调用该函数的代码以及它同时拾取的任何其他内容)并且正在awaited 的 Promise 解析,则该async函数被唤醒并给出解析值继续处理的功能。

\n
\n

与await 一起使用时,为什么不让async 函数返回已解析的promise 值?

\n
\n

因为这会阻塞整个事件循环,这就是为什么异步逻辑(从回调风格的 API 开始)首先被引入到 JS 中。

\n
\n

否则 async wait 似乎有点多余。

\n
\n

考虑这样一种情况,您希望从 API 连续请求多个 URL(这样您就不会在 API 上同时发送太多请求):

\n
const data = [];\nfor (let i = 0; i < urls.length; i++) {\n    const response = await fetch(urls[i]);\n    const response_data = await response.json();\n    data.push(response_data);\n}\n
Run Code Online (Sandbox Code Playgroud)\n

如果你要重写它,await那么你可能会得到一些递归的东西来计算循环的方式。情况会复杂得多。

\n

async/await使得处理复杂的 Promise 组合变得简单,而简单的 Promise 也变得微不足道。

\n
\n

知道 async/await 是使异步代码看起来同步的语法糖。

\n
\n

它在函数内部async并且在函数内部执行此操作。

\n