Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

node.js - Understanding await with Javascript array indexing

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

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

1 Reply

0 votes
by (71.8m points)

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);
})();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...