当前位置:网站首页>[day15] introduce the features, advantages and disadvantages of promise, and how to implement it internally. Implement promise by hand
[day15] introduce the features, advantages and disadvantages of promise, and how to implement it internally. Implement promise by hand
2022-07-03 06:53:00 【Alisone_ li】
introduce promise Characteristics of 、 Advantages and disadvantages , How is it implemented internally , Do it Promise
Promise Basic characteristics
- Promise There are three states :
pending( Have in hand )、fulfilled( Have succeeded )、rejected( Failed ) - Promise Object takes a callback function as an argument , The callback function takes two parameters , They are the callback on success
resolveAnd the callback on failurereject; in addition ,resolveIn addition to normal values , It could be a Promise Instance of object ;rejectThe parameter of is usually a Error Instance of object . thenMethod returns a new one Promise example , And receive two parametersonResolved(fulfilled Status callback );onRejected(rejected Status callback , This parameter is optional )catchMethod returns a new one Promise examplefinallyNo matter what the method is Promise How it will execute , The callback function of this method does not accept any parametersPromise.allMethods will be multiple Promise example , Pack into a new one Promise example , The method accepts a result from Promise An array of objects as parameters (Promise.all() Method can be an array , But must have Iterator Interface , And every member returned is Promise example ), Note that only one instance in the parameter triggerscatchMethod , Will triggerPromise.all()MethodcatchMethod , If an instance in the parameter itself callscatchMethod , Will not triggerPromise.all()MethodcatchMethodPromise.race()Method parameters andPromise.all()The method is the same , Only one instance in the parameter changes state first , The status of this instance will be passed toPromise.race()Method , And return the value asPromise.race()Methods producePromiseThe return value of the instancePromise.resolve()Convert an existing object to Promise object , If the parameter of the method is a Promise object ,Promise.resolve()Nothing will be done ; If parametersthenableobject ( With athenMethod ),Promise.resolve()Convert the object toPromiseObject and execute immediatelythenMethod ; If the argument is a primitive value , Or one that doesn'tthenObject of method , bePromise.resolve()Method returns a new one Promise object , Status asfulfilled, Its parameters will be used asthenIn the methodonResolvedThe parameters of the callback function , IfPromise.resolve()Method without parameters , Will return directly to afulfilledState of Promise object . It should be noted that ,resolve()Of Promise object , It's in this round “ The event loop ”(event loop) At the end of , Not in the next round “ The event loop ” At the beginning of .Promise.reject()Also return a new Promise object , Status asrejected, Any parameter passed in will be used asreject()Parameters of
Promise The advantages of
- 1, Unified asynchronous API
- Promise An important advantage of is that it will gradually be used as an asynchronous browser API, Unify now all kinds of API, And incompatible patterns and techniques .
- 2,Promise And event contrast
- Compared to events ,Promise A one-time result is more suitable for . It is possible to register callback functions before or after the results are calculated , You can get the right value .Promise This advantage is natural . however , Out of commission Promise Handle events triggered multiple times . Chain processing is Promise Another advantage of , But events can't be chained like this .
- 3,Promise And Callback contrast
- Solved the problem of callback to hell , Express the asynchronous operation in the process of synchronous operation .
- 4,Promise The added benefit is that it includes better error handling ( Contains exception handling ), And it's easy to write ( Because you can reuse some synchronous tools , such as Array.prototype.map() ).
Promise The shortcomings of
- 1, Can't cancel Promise, Once it's created, it's executed immediately , Unable to cancel .
- 2, If you do not set the callback function ,Promise An error thrown internally , It doesn't react to the outside .
- 3, When in Pending In the state of , It is impossible to know at what stage ( Just started or almost finished ).
- 4,Promise When the callback is actually executed , Definition Promise That part is actually over , therefore Promise The error stack context of is not very friendly .
Simple code implementation
The simplest Promise Implement a 7 There are three main attributes :state( state )、value( Successful return value )、reason( error message )、resolve Method 、reject Method 、then Method
class Promise{
constructor(executor) {
this.state = 'pending';
this.value = undefined;
this.reason = undefined;
let resolve = value => {
if (this.state === 'pending') {
this.state = 'fulfilled';
this.value = value;
}
};
let reject = reason => {
if (this.state === 'pending') {
this.state = 'rejected';
this.reason = reason;
}
};
try {
// Immediate execution function
executor(resolve, reject);
} catch (err) {
reject(err);
}
}
then(onFulfilled, onRejected) {
if (this.state === 'fulfilled') {
let x = onFulfilled(this.value);
};
if (this.state === 'rejected') {
let x = onRejected(this.reason);
};
}
}
Interview is enough
function myPromise (constructor) {
let self=this;
self.status="pending" // Define the initial state before the state changes
self.value=undefined;// Define status as resolved The state of being
self.reason=undefined;// Define status as rejected The state of being
function resolve(value){
// Two ==="pending", It ensures that the change of state is irreversible
if(self.status==="pending"){
self.value=value;
self.status="resolved";
}
}
function reject(reason){
// Two ==="pending", It ensures that the change of state is irreversible
if(self.status==="pending"){
self.reason=reason;
self.status="rejected";
}
}
// Capture structural anomalies
try{
constructor(resolve,reject);
}catch(e){
reject(e);
}
}
myPromise.prototype.then=function(onFullfilled,onRejected){
let self=this;
switch(self.status){
case "resolved": onFullfilled(self.value); break;
case "rejected": onRejected(self.reason); break;
default:
}
}
// test
var p = new myPromise(
function (resolve,reject) {
resolve(1)
}
);
p.then(
function (x) {
console.log(x)
}
)
// Output 1
Special edition provided by big factory
const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";
function Promise(excutor) {
let that = this; // The current cache promise Instance object
that.status = PENDING; // The initial state
that.value = undefined; // fulfilled In the state of Information returned
that.reason = undefined; // rejected In the state of Reasons for rejection
that.onFulfilledCallbacks = []; // Storage fulfilled The state corresponds to onFulfilled function
that.onRejectedCallbacks = []; // Storage rejected The state corresponds to onRejected function
function resolve(value) {
// value The final value received in the success state
if(value instanceof Promise) {
return value.then(resolve, reject);
}
// In practice, make sure that onFulfilled and onRejected ⽅ Method executes asynchronously ⾏ Line line , And it should be in then ⽅ The method is tuned ⽤ The one used ⼀ New execution after a round of event loop ⾏ Hold in the stack ⾏ Line line .
setTimeout(() => {
// transfer ⽤ use resolve The callback corresponds to onFulfilled function
if (that.status === PENDING) {
// Only by pending state => fulfilled state ( Avoid tuning ⽤ Use it many times resolve reject)
that.status = FULFILLED;
that.value = value;
that.onFulfilledCallbacks.forEach(cb => cb(that.value));
}
});
}
function reject(reason) {
// reason Rejection in failure state
setTimeout(() => {
// transfer ⽤ use reject The callback corresponds to onRejected function
if (that.status === PENDING) {
// Only by pending state => rejected state ( Avoid tuning ⽤ Use it many times resolve reject)
that.status = REJECTED;
that.reason = reason;
that.onRejectedCallbacks.forEach(cb => cb(that.reason));
}
});
}
// Caught in excutor Of board ⾏ Exception thrown in the rowser
// new Promise((resolve, reject) => {
// throw new Error('error in excutor')
// })
try {
excutor(resolve, reject);
} catch (e) {
reject(e);
}
}
Promise.prototype.then = function(onFulfilled, onRejected) {
const that = this;
let newPromise;
// The default value of processing parameters Ensure that the parameters can continue to be executed later ⾏ Line line
onFulfilled = typeof onFulfilled === "function" ? onFulfilled : value => value;
onRejected = typeof onRejected === "function" ? onRejected : reason => {
throw reason;
};
if (that.status === FULFILLED) {
// Success state
return newPromise = new Promise((resolve, reject) => {
setTimeout(() => {
try{
let x = onFulfilled(that.value);
resolvePromise(newPromise, x, resolve, reject); // new promise resolve On ⼀ One onFulfilled The return value of
} catch(e) {
reject(e); // Before capture ⾯ Noodles onFulfilled Exception thrown in then(onFulfilled, onRejected);
}
});
})
}
if (that.status === REJECTED) {
// Failure state
return newPromise = new Promise((resolve, reject) => {
setTimeout(() => {
try {
let x = onRejected(that.reason);
resolvePromise(newPromise, x, resolve, reject);
} catch(e) {
reject(e);
}
});
});
}
if (that.status === PENDING) {
// Waiting state
// When asynchronous call ⽤ use resolve/rejected when take onFulfilled/onRejected The collection is staged in the collection
return newPromise = new Promise((resolve, reject) => {
that.onFulfilledCallbacks.push((value) => {
try {
let x = onFulfilled(value);
resolvePromise(newPromise, x, resolve, reject);
} catch(e) {
reject(e);
}
});
that.onRejectedCallbacks.push((reason) => {
try {
let x = onRejected(reason);
resolvePromise(newPromise, x, resolve, reject);
} catch(e) {
reject(e);
}
});
});
}
};
边栏推荐
- DNS forward query:
- Laravel框架 踩坑(一)
- Sorting out the core ideas of the pyramid principle
- Winter vacation work of software engineering practice
- Pytest -- write and manage test cases
- 2022 - 06 - 23 vgmp - OSPF - Inter - Domain Security Policy - nat Policy (Update)
- Derivation of variance iteration formula
- Floating menu operation
- Abstract learning
- How can I split a string at the first occurrence of “-” (minus sign) into two $vars with PHP?
猜你喜欢

2022 East China Normal University postgraduate entrance examination machine test questions - detailed solution

2022年华东师范大学计科考研复试机试题-详细题解

Practice of enterprise ab/testing platform

这两种驱蚊成份对宝宝有害,有宝宝的家庭,选购驱蚊产品要注意

Personally design a highly concurrent seckill system

Numerical method for solving optimal control problem (I) -- gradient method

The pressure of large institutions in the bear market has doubled. Will the giant whales such as gray scale, tether and micro strategy become 'giant thunder'?

【5G NR】UE注册流程

【类和对象】深入浅出类和对象

My 2020 summary "don't love the past, indulge in moving forward"
随机推荐
多个全局异常处理类,怎么规定执行顺序
A letter to graduating college students
[open source project recommendation colugomum] this group of undergraduates open source retail industry solutions based on the domestic deep learning framework paddlepadddle
2022 cisp-pte (III) command execution
centos php7.3安装redis扩展
IC_EDA_ALL虚拟机(丰富版):questasim、vivado、vcs、verdi、dc、pt、spyglass、icc2、synplify、INCISIVE、IC617、MMSIM、工艺库
Centos切换安装mysql5.7和mysql8.0
学习笔记 -- k-d tree 和 ikd-Tree 原理及对比
How to plan well?
Interface learning
error C2017: 非法的转义序列
JMeter JSON extractor extracts two parameters at the same time
Pytest attempts to execute the test case without skipping, but the case shows that it is all skipped
[LeetCode]404. Sum of left leaves
Summary of remote connection of MySQL
New knowledge! The virtual machine network card causes your DNS resolution to slow down
mysql误删root账户导致无法登录
php安装swoole扩展
Understand software testing
The 10000 hour rule won't make you a master programmer, but at least it's a good starting point