简体   繁体   English

异步等待回调行为

[英]async-await callback behaviour

I'm trying to understand async-await behaviour with callbacks. 我试图了解回调的异步等待行为。 Firstly, let's look at this function: 首先,让我们看一下这个函数:

const assert = require('assert')

async function promiseReturner() {
  return Promise.resolve(Promise.resolve(Promise.resolve(Promise.resolve(42))))
}

(async function() {
  assert.equal(await promiseReturner(), 42)
})()

This leads me to safely conclude that the await keyword always resolves a promise, no matter what. 这使我可以安全地得出结论,无论如何, await关键字始终可以解决承诺。

Now here's a function that returns a number after a second: 现在,这里有个函数可以在一秒钟后返回一个数字:

async function addTenAndReturnNumber(number) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(number)
    }, 1000)
  })
}

I ran two experiments with this. 我对此进行了两个实验。 First the forEach loop. 首先是forEach循环。

(async function() {
  let variable;
  const result = [41, 42, 43].forEach(async (number) => {
    variable = await addTenAndReturnNumber(number)
  })
  console.log(variable) // undefined
})()

Okay, so great. 好的,太好了。 It would appear that the forEach callback evaluated in the next tick, and hence variable is undefined (although that's exactly what one would think await shouldn't do). 似乎forEach回调在下一个刻度中求值,因此variable未定义(尽管这正是人们认为await不应该做的事情)。 Let's try map next: 接下来尝试map

(async function() {
  const result = [41, 42, 43].map(async (number) => {
    return await addTenAndReturnNumber(number)
  })
  console.log(result) // [Promise {}, Promise {}, Promise {}]
})()

I would assume that it would either return [51, 52, 53] , or as before an undefined 我假设它会返回[51, 52, 53] ,或者像之前一样undefined

Please note that my question is around the behaviour and why this is designed like so - is this a conscious decision on the part of the spec? 请注意,我的问题与行为有关,为什么要这样设计-规范方面是否有意识地做出决定? I am aware that I can use a for...of or a Promise.all 我知道我可以使用for...ofPromise.all

Thanks! 谢谢!

async functions always return a promise (if you await the promise, you'll get its actual value). async函数总是返回一个承诺(如果您await该承诺,您将获得其实际值)。

Passing an async function to map() will return an array of what the async function returns, which is, of course, a promise. async函数传递给map()将返回一个async函数返回的数组,这当然是一个承诺。

Your forEach() callback runs immediately, but once it hits the await , it will only resume running after the promise resolves (which is guaranteed to be after your code finishes running). 您的forEach()回调会立即运行,但是一旦到达await ,它将仅在promise解析后(保证在您的代码完成运行之后)继续运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM