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?
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.
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With