Copyright NOTICE: This work is licensed under the Creative Commons Attribution-NonCommercial use-Share 4.0 International license agreement in the same way. Reprint please indicate source Http://blog.csdn.net/azureternite
Directory (?) [+]
The concept of promise
The Promise object is used for asynchronous (asynchronous) computations: A Promise object represents an operation that has not yet been completed but is expected to be completed in the future.
Several states of promise:
- Pending: The initial state, that is, the execution of the wait operation
- Fulfilled: Successful operation
- Rejected: Failed operation
The state of the pending can either be converted to fulfilled or rejected, and when the state changes, the Promise.then (onfulfilled, onrejected) method is called
Basic usage of Promise
1. First create an instance of promise
var promise = new Promise(function(resolve, reject){ //do something if(success){ resolve(value); } else { reject(value); }});
Using promise to encapsulate asynchronous functions
The IO operation in node. JS is asynchronous, so it's easy to fall into the callback pit during the writing of the async program.
Knowing the basic call procedure of promise, we can use it to encapsulate asynchronous functions.
1. Defining functions
functionSendRequest(){ReturnNew Promise (function(Resolve, Reject) { var req = http.request (options, function(res) { var data = '; Res.on (' data ', function(chunk) {data + = chunk;}); Res.on (' end ', function() { ////Successful call resolve (data);}); }); Req.on (' error ', function(err) { //] call reject (ERR) after failure;}); Req.end ();});
2. Calling functions
sendRequest().then(function(data){ console.log(data);}).catch(function(err){ console.log(err);});
node. JS encapsulates an asynchronous function with ES6 native promise