Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
139 views
Welcome To Ask or Share your Answers For Others

1 Answer

await's operator precedence is 17. In contrast, member access, eg [0], has a higher precedence of 20.

So

await myFn()[0];

is equivalent to

await (myFn()[0]);

It's valid syntax because any expression can be awaited (it just doesn't make much sense to do so for a non-Promise).

(async () => {
  const contains5 = await 5;
  console.log(contains5);
})();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...