Home >Web Front-end >JS Tutorial >Why is Using Async/Await Inside a Promise Constructor an Anti-Pattern?

Why is Using Async/Await Inside a Promise Constructor an Anti-Pattern?

Susan Sarandon
Susan SarandonOriginal
2025-01-05 11:23:41755browse

Why is Using Async/Await Inside a Promise Constructor an Anti-Pattern?

Promise Constructor Anti-Pattern: Using Async/Await Within Promise()

In async programming, using async/await within the executor function of a Promise() constructor is considered an anti-pattern. This practice involves embedding promises within promises, leading to potential errors that may not be propagated correctly.

Consider the code snippet below:

const { eachLimit } = require("async");

function myFunction() {
 return new Promise(async (resolve, reject) => {
   eachLimit((await getAsyncArray), 500, (item, callback) => {
     // do other things that use native promises.
   }, (error) => {
     if (error) return reject(error);
     // resolve here passing the next value.
   });
 });
}

In this example, the myFunction is called and the Promise constructor is invoked with an async function as its executor. This pattern is problematic because it can result in errors not being propagated properly. If any errors occur within the eachLimit callback, they will not be caught by the Promise and will silently fail.

Additionally, using async/await within the Promise constructor can make these traps even more surprising. For instance, compare the following:

let p = new Promise(resolve => {
  ""(); // TypeError
  resolve();
});

(async () => {
  await p;
})().catch(e => console.log("Caught: " + e)); // Catches it.

In this example, the TypeError is thrown synchronously within the executor function. However, when the Promise is awaited using async/await, the error is caught by the catch block, even though it occurred before the Promise was resolved. This behavior can lead to confusion and unexpected results.

To avoid this anti-pattern, it is recommended to avoid using async/await within the executor function of a Promise() constructor. Instead, use the then or catch methods to chain additional promises and handle errors.

The above is the detailed content of Why is Using Async/Await Inside a Promise Constructor an Anti-Pattern?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Clean Code Zero to OneNext article:Clean Code Zero to One