Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chain async functions

In an async function, I can get an asynchronous value like so:

const foo = await myAsyncFunction()

If I want to call a method on the result, with a sync function I'd do something like myAsyncFunction().somethingElse()

Is it possible to chain calls with async functions, or do you have to assign a new variable for each result?

like image 272
Asherlc Avatar asked Jul 28 '16 19:07

Asherlc


People also ask

What is an async function JavaScript?

An async function is a function declared with the async keyword, and the await keyword is permitted within it. The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.

Can two async functions run at the same time?

You can call multiple asynchronous functions without awaiting them. This will execute them in parallel. While doing so, save the returned promises in variables, and await them at some point either individually or using Promise. all() and process the results.

Why async await over simple promise chains?

Promise chains can become difficult to understand sometimes. Using Async/Await makes it easier to read and understand the flow of the program as compared to promise chains.


1 Answers

You can await in an expression, no need to assign it to a new variable. (Although assigning it to a variable is probably more readable.)

const foo = await (await myAsyncFunction()).somethingElseAsync() 

Or if you want to call a sync method on the result:

const foo = (await myAsyncFunction()).somethingElseSync() 
like image 165
Tamas Hegedus Avatar answered Oct 14 '22 11:10

Tamas Hegedus