Skip to content
Advertisement

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?

Advertisement

Answer

I prefer to assign the first result to an intermediate variable, I personally find it more readable.

If you prefer, you can await in an expression, no need to assign it. All you have to do is to use parentheses. See my example:

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

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

const foo = (await myAsyncFunction()).somethingElseSync()
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement