Home Web Front-end JS Tutorial Quickly avoid pitfalls and talk about 5 common mistakes in using promises!

Quickly avoid pitfalls and talk about 5 common mistakes in using promises!

Dec 08, 2021 am 10:22 AM
javascript promise Common mistakes

This article will share with you 5 common mistakes when using promises to help you avoid pitfalls quickly. I hope it will be helpful to you!

Quickly avoid pitfalls and talk about 5 common mistakes in using promises!

#Promise provides an elegant way to handle asynchronous operations in JS. This is also a solution to avoid "callback hell". However, not many developers understand what's involved. Therefore, many people tend to make mistakes in practice. [Related recommendations: javascript learning tutorial]

In this article, we introduce five common mistakes when using promises, and hope that everyone can avoid these mistakes.

1. Avoid Promise Hell

Usually, Promise is used to avoid callback hell. But abusing them can also lead to Promises being hell.

userLogin('user').then(function(user){
    getArticle(user).then(function(articles){
        showArticle(articles).then(function(){
            //Your code goes here...
        });
    });
});
Copy after login

In the above example, we have three nested promises for userLogin, getararticle and showararticle. This way the complexity will grow in proportion to the lines of code and it may become unreadable.

To avoid this, we need to unnest the code, return getArticle from the first then, and then in the second then to handle it.

userLogin('user')
  .then(getArticle)
  .then(showArticle)
  .then(function(){
       //Your code goes here...
});
Copy after login

2. Use <span style="font-size: 18px;">try/catch</span> block

in Promise

Normally, we use try/catch blocks to handle errors. However, using try/catch within a Promise object is not recommended.

This is because if there are any errors, the Promise object will be automatically handled within catch.

ew Promise((resolve, reject) => {
  try {
    const data = doThis();
    // do something
    resolve();
  } catch (e) {
    reject(e);
  }
})
  .then(data => console.log(data))
  .catch(error => console.log(error));
Copy after login

In the above example, we used the try/catch block inside the Promise.

However, Promise itself will catch all errors (even typos) within its scope without the need for a try/catch block. It ensures that all exceptions thrown during execution are caught and converted into rejected Promises.

new Promise((resolve, reject) => {
  const data = doThis();
  // do something
  resolve()
})
  .then(data => console.log(data))
  .catch(error => console.log(error));
Copy after login

Note: It is crucial to use the .catch() block within a Promise block. Otherwise, your test cases may fail and the application may crash during the production phase.

3. Use asynchronous functions within Promise blocks

Async/Await is a more advanced syntax, Used to handle multiple Promises in synchronous code. When we use the async keyword before a function declaration, it will return a Promise. We can use the await keyword to stop the code until the Promise we are waiting for is resolved or rejected. .

However, when you put an Async function inside a Promise block, there will be some side effects.

Suppose we want to do an asynchronous operation in the Promise block, so we use the async keyword, but unfortunately our code throws an error.

This way, even if you use a catch() block or wait for your Promise inside a try/catch block, we cannot handle the error immediately. Please see the example below.

// 此代码无法处理错误
new Promise(async () => {
  throw new Error(&#39;message&#39;);
}).catch(e => console.log(e.message));

(async () => {
  try {
    await new Promise(async () => {
      throw new Error(&#39;message&#39;);
    });
  } catch (e) {
    console.log(e.message);
  }
})();
Copy after login

When I encounter an async function inside a Promise block, I'm trying to keep the async logic outside the Promise block to keep it synchronized. It works 9 times out of 10.

However, in some cases, an async function may be required. In this case, there is no choice but to manage it manually using try/catch blocks.

new Promise(async (resolve, reject) => {
  try {
    throw new Error(&#39;message&#39;);
  } catch (error) {
    reject(error);
  }
}).catch(e => console.log(e.message));


//using async/await
(async () => {
  try {
    await new Promise(async (resolve, reject) => {
      try {
        throw new Error(&#39;message&#39;);
      } catch (error) {
        reject(error);
      }
    });
  } catch (e) {
    console.log(e.message);
  }
})();
Copy after login

4. Execute the Promise block immediately after creating the Promise

As for the following code snippet, if we put the code snippet in the call HTTP Where requested, it will be executed immediately.

const myPromise = new Promise(resolve => {
  // code to make HTTP request
  resolve(result);
});
Copy after login

The reason is that this code is wrapped in a Promise constructor. However, some may think that it is only triggered after the then method of myPromise is executed.

However, the truth is not so. In contrast, when a Promise is created, the callback is executed immediately.

This means that by the time the following line is reached after establishing myPromise, the HTTP request is most likely already running, or at least in a scheduled state.

Promises are always eager to execute the process.

But what should you do if you want to execute Promises in the future? What if I don't want to make an HTTP request now? Is there some magical mechanism built into Promises that allows us to do this?

The answer is to use functions. Functions are a time-consuming mechanism. They will only execute if the developer explicitly calls them with (). Simply defining a function doesn't get us anywhere. So, the most efficient way to make a Promise lazy is to wrap it in a function!

const createMyPromise = () => new Promise(resolve => {
  // HTTP request
  resolve(result);
});
Copy after login

对于HTTP请求,Promise 构造函数和回调函数只有在函数被执行时才会被调用。所以现在我们有一个懒惰的Promise,只有在我们需要的时候才会执行。

5. 不一定使用 Promise.all() 方法

如果你已经工作多年,应该已经知道我在说什么了。如果有许多彼此不相关的 Promise,我们可以同时处理它们。

Promise 是并发的,但如你一个一个地等待它们,会太费时间,Promise.all()可以节省很多时间。

记住,Promise.all() 是我们的朋友
const { promisify } = require(&#39;util&#39;);
const sleep = promisify(setTimeout);

async function f1() {
  await sleep(1000);
}

async function f2() {
  await sleep(2000);
}

async function f3() {
  await sleep(3000);
}


(async () => {
  console.time(&#39;sequential&#39;);
  await f1();
  await f2();
  await f3();
  console.timeEnd(&#39;sequential&#39;);  
})();
Copy after login

上述代码的执行时间约为 6 秒。但如果我们用 Promise.all() 代替它,将减少执行时间。

(async () => {
    console.time(&#39;concurrent&#39;);
    await Promise.all([f1(), f2(), f3()]);
    console.timeEnd(&#39;concurrent&#39;); 
  })();
Copy after login

总结

在这篇文章中,我们讨论了使用 Promise 时常犯的五个错误。然而,可能还有很多简单的问题需要仔细解决。

如果你还有更多相关的错误,欢迎留言一起讨论。

英文原文地址:https://blog.bitsrc.io/5-common-mistakes-in-using-promises-bfcc4d62657f

作者:Ravidu Perera

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of Quickly avoid pitfalls and talk about 5 common mistakes in using promises!. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

Keeping your word: The pros and cons of delivering on your promises Keeping your word: The pros and cons of delivering on your promises Feb 18, 2024 pm 08:06 PM

In daily life, we often encounter problems between promises and fulfillment. Whether in a personal relationship or a business transaction, delivering on promises is key to building trust. However, the pros and cons of commitment are often controversial. This article will explore the pros and cons of commitments and give some advice on how to keep your word. The promised benefits are obvious. First, commitment builds trust. When a person keeps his word, he makes others believe that he is a trustworthy person. Trust is the bond established between people, which can make people more

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Learn more about Promise.resolve() Learn more about Promise.resolve() Feb 18, 2024 pm 07:13 PM

Detailed explanation of Promise.resolve() requires specific code examples. Promise is a mechanism in JavaScript for handling asynchronous operations. In actual development, it is often necessary to handle some asynchronous tasks that need to be executed in sequence, and the Promise.resolve() method is used to return a Promise object that has been fulfilled. Promise.resolve() is a static method of the Promise class, which accepts a

See all articles