How to call an async function within a Promise .then with JavaScript?

Sometimes, we want to call an async function within a Promise .then with JavaScript.

In this article, we’ll look at how to call an async function within a Promise .then with JavaScript.

How to call an async function within a Promise .then with JavaScript?

To call an async function within a Promise .then with JavaScript, we can return the result of the async function call in the then callback.

For instance, we write:

const f = async () => 'foo'

Promise.resolve(1)
  .then((res) => {
    console.log(res)
    return f()
  })
  .then((res) => {
    console.log(res)
  })

to create the f async function.

Then we call f in the then callback to trigger the call of the 2nd then callback which logs the resolved value of the promise returned by f.

Therefore, we see

1
"foo"

logged.

Conclusion

To call an async function within a Promise .then with JavaScript, we can return the result of the async function call in the then callback.