


Using Promise to encapsulate asynchronous functions in NodeJS_node.js
In the process of writing Node.js, continuous IO operations may lead to a "pyramid nightmare". Multiple nesting of callback functions makes the code difficult to maintain. Use CommonJs's Promise to encapsulate asynchronous functions and use a unified chain. API to get rid of the nightmare of multiple callbacks.
The non-blocking IO model provided by Node.js allows us to use callback functions to handle IO operations. However, when continuous IO operations are required, your callback functions will be nested multiple times, making the code very unsightly and difficult to maintain. And there may be a lot of duplicate code for error handling, the so-called "Pyramid of Doom".
step1(function (value1) {
Step2(value1, function(value2) {
step3(value2, function(value3) {
step4(value3, function(value4) {
// Do something with value4
});
});
});
});
This is actually a problem with the Control flow of Node.js. There are many solutions to this problem, such as using async, or eventProxy, etc. However, the theme of this article is to use Promise in the CommonJs specification to solve this problem.
What is Promise?
There are many Promise specifications of CommonJs. We generally discuss the Promise/A specification, which defines the basic behavior of Promise.
A Promise is an object that usually represents an asynchronous operation that may be completed in the future. This operation may succeed or fail, so a Promise object generally has three states: Pending, Fulfilled, and Rejected. Represents incomplete, successful completion and operation failure respectively. Once the state of the Promise object changes from Pending to Fulfilled or Rejected, its state cannot be changed.
A Promise object usually has a then method, which allows us to manipulate the value returned after possible success in the future or the reason for failure. The then method looks like this:
promise.then(onFulfilled, onRejected)
Obviously, the then method accepts two parameters, which are usually two functions. One is used to handle the results after the operation succeeds, and the other is used to handle the reasons after the operation fails. The first of these two functions The two parameters are the result after success and the reason for failure respectively. If the parameter passed to the then method is not a function, this parameter will be ignored.
The return value of the then method is a Promise object. This feature allows us to chain call then to achieve the effect of controlling the flow. There are many detailed issues here, such as value transfer or error handling. The specification of Promise is defined as follows:
The return value of the onFulfilled or onRejected function is not a Promise object, then this value will be used as the first parameter of onFulfilled in the next then method. If the return value is a Promise object, why is the return value of the then method the Promise object?
If an exception is thrown in the onFulfilled or onRejected function, the status of the Promise object returned by the then method will be changed to Rejected. If the Promise object calls then, the Error object will be used as the first parameter of the onRejected function
If the Promise status becomes Fulfilled and no onFulfilled function is provided in the then method, the Promise object status returned by the then method becomes Fulfilled and the successful result is the result of the previous Promise. The same is true for Rejected.
In addition, onFulfilled and onRejected are executed asynchronously.
Standard implementation: q
The above is the specification of Promise, and what we need is its implementation. q is a library with better implementation specifications for Promise/A.
First we need to create a Promise object. The specifications for the creation of Promise objects are in Promise/B. I will not give a detailed explanation here, just go to the code.
Function(flag){
var defer = q.defer();
fs.readFile("a.txt", function(err, data){
If(err) defer.reject(err);
else defer.resolve(data);
});
return defer.promise;
}
Most implementations of Promise are similar in the creation of Promise. By creating a defer object with a promise attribute, if the value is successfully obtained, defer.resolve(value) is called. If it fails, defer.reject(reason) is called. Finally, return the promise attribute of defer. This process can be understood as calling defer.resolve to change the Promise's status to Fulfilled, and calling defer.reject to change the Promise's status to Rejected.
When faced with a series of continuous asynchronous methods, how to use Promise to write beautiful code? Take a look at the example below.
promise0.then(function(result){
// dosomething
return result;
}).then(function(result) {
// dosomething
return promise1; }).then(function(result) {
// dosomething
}).catch(function(ex) {
console.log(ex);
}).finally(function(){
console.log("final");
});
It seems good, the code is more maintainable and beautiful, so what if you want concurrency?
console.log(arguments);
}).then(function(){
console.log("done");
}).catch(function(err){
console.log(err);
});
Conclusion
This article mainly introduces the use of Promise to solve Node.js control flow problems, but Promise can also be applied to the front end. EMCAScript6 has provided native API support. It should be pointed out that Promise is not the only solution. async is also a good choice and provides a more friendly concurrency control API. However, I think Promise has more advantages when encapsulating functions with asynchronous methods.Okay, this article ends here, I hope it can be helpful to everyone.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

Vue is a popular front-end framework, and you often encounter various errors and problems when developing applications. Among them, Uncaught(inpromise)TypeError is a common error type. In this article, we will discuss its causes and solutions. What is Uncaught(inpromise)TypeError? Uncaught(inpromise)TypeError error usually appears in

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

Use Promise objects to change ordinary functions to return Promise to solve the problem of callback hell. Understand the success and failure calling logic of Promise and make adjustments flexibly. Understand the core knowledge, use it first, and slowly integrate and absorb the knowledge.

The promise object states are: 1. pending: initial state, neither success nor failure state; 2. fulfilled: means the operation was successfully completed; 3. rejected: means the operation failed. Once a Promise object is completed, it will change from the pending state to the fulfilled or rejected state, and cannot change again. Promise objects are widely used in JavaScript to handle asynchronous operations such as AJAX requests and timed operations.

Browser compatibility: Which browsers support Promises? As the complexity of web applications continues to increase, developers are eager to solve the problem of asynchronous programming in JavaScript. In the past, developers often used callback functions to handle asynchronous operations, but this resulted in code that was complex and difficult to maintain. To solve this problem, ECMAScript6 introduced Promise, which provides a more intuitive and flexible way to handle asynchronous operations. Promise is a method used to handle exceptions

Advantages: asynchronous and non-blocking, does not block the main thread; improves code readability and maintainability; built-in error handling mechanism.

In front-end js learning, the most uncomfortable thing for everyone is the problem of asynchronousness. To solve problems such as asynchronous and callback hell, you must learn promises. For most front-end programmers, promises are simply a nightmare. This article starts from the easy-to-understand Angle is used as the entry point to help everyone easily master promises.
