Ad
Using Await Inline On Variable In Outer Scope
(async function iife () {
const numbers = [1, 2, 3, 4]
let count = 0
async function returnNumberAsync (number) {
return new Promise(resolve => {
setTimeout(() => resolve(number), 0)
})
}
await Promise.all(numbers.map(async number => {
count += await returnNumberAsync(number)
}))
console.log(count)
})()
This snippet logs 4
to the console, which is completely beyond me. As soon as I assign the promised value inside map
to its own local variable …
const result = await returnNumberAsync(number)
count += result;
… it logs 10
like I'd expect. What's happening when I count += await …
??
Ad
Answer
When you do count += await <expression>
, the initial value of count
to be added to the resolve value is saved before the await
part is resolved. So
count += await returnNumberAsync(number)
is like
count = count + await returnNumberAsync(number)
as you can see:
(async function iife () {
const numbers = [1, 2, 3, 4]
let count = 0
async function returnNumberAsync (number) {
return new Promise(resolve => {
setTimeout(() => resolve(number), 0)
})
}
await Promise.all(numbers.map(async number => {
count = count + await returnNumberAsync(number)
}))
console.log(count)
})()
In each of the 4 closures, count
is seen to be 0 before the await
s resolve, so only in the final await
microtask, where it resolves to
count += await returnNumberAsync(4)
// or
count = 0 + await returnNumberAsync(4)
// or
count = 4
does 4
get assigned to count
. The fact that other numbers were assigned to count
earlier is ignored. They did happen, but the assignment of the final iteration is all you see with the current code.
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad