Thought leadership from the most innovative tech companies, all in one place.

Be Careful of Passing an Async Function as a Parameter in JavaScript

The async function allows multiple await expressions in its scope, which can pause the execution until the awaited Promise is resolved. It combines controllable promise chaining and generator function features.

Let's examine two examples and find out if they produce the same console output. The answer is no:

Example 1 Output:

"start"

1

2

3

"end"

Example 2 Output:

"start"

"end"

1

2

3

When passing an async function as a parameter, especially to a third-party function, it's crucial to be cautious as you might lose control of its execution.

1. Async/Await Explanation

async keyword and await expression work together, where await can only pause the execution within its corresponding async function's scope. Inner await expressions won't pause the execution in the outer scope.

2. Pause Outer Scope's Execution with Inner Scope Await

To pause the execution in the outer scope from the inner scope's await expression, the behavior depends on how the function handler deals with the async function:

(1) If the handler function is synchronous, you must link the inner scope's await promise to the outer scope's await by returning a promise from the handlerFn. The returned promise's resolution should depend on the inner scope's await.

(2) If the handler function is asynchronous, create a promise in the handler function whose resolution depends on the inner scope's await, and return it to the outer scope.

When passing an async function as a parameter to a third-party handler function, it's essential to understand the type of the handler function (async or not) and how your function will be executed before doing so.

In conclusion, while async/await is powerful, there are potential pitfalls to be aware of, such as the interactions between inner and outer scopes and error handling in async functions. Understanding these intricacies will help you use async/await effectively in your projects.




Continue Learning