I encountered an issue in Javascript code where an await
used in conjunction with array indexing a return value was behaving differently than I expected.
I have an async function returning an array, similar to this example:
const myFn = async () => {
let result = [];
for(i=0; i<100; i++) {
result.push(i);
}
return result;
};
const a = await myFn()[0]; // -> undefined
const result = await myFn();
const b = result[0]; // -> 0
Here I see that a
is undefined
, while b
is 0. I was expecting that both a
and b
would be assigned 0. Then I also found that an await on an array index is valid syntax, which explains why the two values above are different if the await statement only targets the highest level operation.
const myArr = [ 'a', 'b', 'c' ];
const a = await myArr[0];
So my question is, what is actually happening when you await an array index and why is this valid syntax?
question from:
https://stackoverflow.com/questions/66050816/understanding-await-with-javascript-array-indexing 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…