Home > Common Problem > body text

What is the principle of promise?

爱喝马黛茶的安东尼
Release: 2020-01-06 15:19:44
Original
9247 people have browsed it

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 operation

getData(function(a){  
    getMoreData(a, function(b){
        getMoreData(b, function(c){ 
            getMoreData(c, function(d){ 
                getMoreData(d, function(e){ 
                    ...
                });
            });
        });
    });
});
Copy after login

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
})
Copy after login

Make the above code more concise

getData()
.then(a => getMoreData(a))
.then(b => console.log(b));
Copy after login

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);
})
Copy after login

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);
});
Copy after login

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 created

Fulfilled can be understood as the successful state

Rejected 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 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;
Copy after login

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template