1. Promise application scenarios
1 Solve the callback hell
For example, we may often need to request a piece of data asynchronously as an input parameter for the next asynchronous operation
getData(function(a){ getMoreData(a, function(b){ getMoreData(b, function(c){ getMoreData(c, function(d){ getMoreData(d, function(e){ ... }); }); }); }); });
You can find that the above code looks very scary, nested layer by layer, if complex logic is added Judgment, code readability will become very poor.
But if you use promise:
function getData() { return new Promise(function (resolve, reject) { resolve(1); }); } function getMoreData(arg) { return new Promise(function (resolve, reject) { resolve(arg + 10); }); } getData().then(function (a) { console.log(a); // 1 return getMoreData(a); }).then(function (b) { console.log(b); // 11 })
Make the above code more concise
getData() .then(a => getMoreData(a)) .then(b => console.log(b));
2 Promise can be used to obtain or process a certain request after multiple requests are sent. A result
// 两个数据都回来之后再进行操作 let fs = require('fs'); fs.readFile('./1.txt', 'utf8', function (err, data) { console.log(data); }) fs.readFile('./2.txt', 'utf8', function (err, data) { console.log(data); }) 使用promise的话就可以实现: let fs = require('fs'); function read(url){ return new Promise(function(resolve,reject){ fs.readFile(url,'utf8',function(err,data){ if(err)reject(err); resolve(data); }) }) } Promise.all([read('1.txt'),read('2.txt')]).then(data=>{ console.log(data); },err=>{ console.log(err); });
2. Promise principle implementation
1. The simplest implementation
Based on the above application scenario, it is found that promise can have three states, They are pedding, Fulfilled and Rejected respectively.
The initial state when the Pending Promise object instance is created
Fulfilled can be understood as the successful state
Rejected can be understood as the failed state
Construct a Promise The instance needs to pass a function to the Promise constructor. The function passed in needs to have two formal parameters, both of which are function type parameters. They are resolve and reject respectively.
There is also a then method on Promise. The then method is used to specify the operation to be performed when the state of the Promise object changes. The first function (onFulfilled) is executed when resolves, and the second function (onRejected) is executed when rejects. )
When the status changes to resolve, it cannot change to reject, and vice versa.
Based on the above description we can implement such a promise
function Promise(executor){ //executor执行器 let self = this; self.status = 'pending'; //等待态 self.value = undefined; // 表示当前成功的值 self.reason = undefined; // 表示是失败的值 function resolve(value){ // 成功的方法 if(self.status === 'pending'){ self.status = 'resolved'; self.value = value; } } function reject(reason){ //失败的方法 if(self.status === 'pending'){ self.status = 'rejected'; self.reason = reason; } } executor(resolve,reject); } Promise.prototype.then = function(onFufiled,onRejected){ let self = this; if(self.status === 'resolved'){ onFufiled(self.value); } if(self.status === 'rejected'){ onRejected(self.reason); } } module.exports = Promise;
The above is the detailed content of promise principle. For more information, please follow other related articles on the PHP Chinese website!