Home >Common Problem >What is the principle of promise?
#1. Promise application scenarios
1. Solve the callback hell
For example, we may often need to request a piece of data asynchronously and then use it as an input parameter for the next asynchronous operationgetData(function(a){ getMoreData(a, function(b){ getMoreData(b, function(c){ getMoreData(c, function(d){ getMoreData(d, function(e){ ... }); }); }); }); });can be found The above code looks very scary, nested layer by layer, and if complex logical judgments are added, the readability of the code 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 implemented after multiple requests are sent. Then get or process a certain 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); })You can achieve it by using 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. Implementation of promise principle
1. The simplest implementation
Based on the above application scenario, it is found that promise can have three states, namely pedding, Fulfilled, and Rejected.The initial state when the Pending Promise object instance is createdFulfilled can be understood as the successful stateRejected can be understood as the failed state
·Constructing a Promise instance requires passing 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 is executed when resolving. (onFulfilled), execute the second function (onRejected) when rejecting
·When the state changes to resolve, it cannot change to reject, and vice versa Same reason.
Based on the above description we can implement such a promisefunction 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;For more
FAQ, please visit the PHP Chinese website.
The above is the detailed content of What is the principle of promise?. For more information, please follow other related articles on the PHP Chinese website!