Chain async functions

Asherlc picture Asherlc · Jul 28, 2016 · Viewed 12.6k times · Source

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?

Answer

Tamas Hegedus picture Tamas Hegedus · Jul 28, 2016

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