Home > OS >  Using ((await asyncCall))[0] instead of await asyncCall()
Using ((await asyncCall))[0] instead of await asyncCall()

Time:09-13

I came across the below Typescript code and want to know why it assigns myArray with ((await asyncRPCCall))[0] as opposed to just doing assignment with await asyncRPCCall(). Why put the results in () and return the first element? What's the difference?

export class myClass {

 static async myFunction(): Promise<void> {

   const myArray: Array<Array<string>> = ((await asyncRPCCall))[0]
   console.log(myArray) // [['a','b','c','d'],['e','f','g','h']]

 }

}

CodePudding user response:

Most likely the caller wanted the first element from the async response.

It seems like asyncRPCCall() returns an array and the caller just wants the first element.

You could assign the result to a temp array and then get the first element though.

CodePudding user response:

why it assigns myArray with ((await asyncRPCCall))[0] as opposed to just doing assignment with await asyncRPCCall()

Because asyncRPCCall is a promise and not a function that return a promise when it is called.

Why put the results in ()

asyncRPCCall is a promise that resolves to an array.

The expression (await asyncRPCCall)[0] awaits the promise, then reads the first member of the array.

await asyncRPCCall[0] would try to treat asyncRPCCall as an array, read the first value from it, then await the promise that that value is. Since asyncRPCCall is a promise and not an array, this would be wrong.

and return the first element?

The code wants the first member of the array.

  • Related