当前位置:网站首页>[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);
}
});
});
}
};
边栏推荐
- 【5G NR】UE注册流程
- [open source project recommendation colugomum] this group of undergraduates open source retail industry solutions based on the domestic deep learning framework paddlepadddle
- In depth analysis of reentrantlock fair lock and unfair lock source code implementation
- The 10000 hour rule won't make you a master programmer, but at least it's a good starting point
- 【code】if (list != null && list.size() > 0)优化,集合判空实现方式
- Summary of the design and implementation of the weapon system similar to the paladin of vitality
- Operation principle of lua on C: Foundation
- Condition annotation in uni-app realizes cross segment compatibility, navigation jump and parameter transfer, component creation and use, and life cycle function
- [untitled]
- Realize PDF to picture conversion with C #
猜你喜欢

远端rostopic的本地rviz调用及显示

数值法求解最优控制问题(一)——梯度法

SSH link remote server and local display of remote graphical interface

JMeter JSON extractor extracts two parameters at the same time

“我为开源打榜狂”第一周榜单公布,160位开发者上榜

Reading notes of "learn to ask questions"

【5G NR】UE注册流程

Yolov2 learning and summary

Software testing learning - the next day

Example of joint use of ros+pytoch (semantic segmentation)
随机推荐
熊市里的大机构压力倍增,灰度、Tether、微策略等巨鲸会不会成为'巨雷'?
instanceof
Abstract learning
Jenkins
Interface learning
Notes on the core knowledge of Domain Driven Design DDD
Dbnet: real time scene text detection with differentiable binarization
Winter vacation work of software engineering practice
golang操作redis:写入、读取kv数据
Software testing assignment - the next day
How can the server set up multiple interfaces and install IIS? Tiantian gives you the answer!
The 10000 hour rule won't make you a master programmer, but at least it's a good starting point
Ruoyi interface permission verification
Basic teaching of crawler code
[classes and objects] explain classes and objects in simple terms
Pytest attempts to execute the test case without skipping, but the case shows that it is all skipped
Software testing learning - day one
Stream stream
ssh链接远程服务器 及 远程图形化界面的本地显示
These two mosquito repellent ingredients are harmful to babies. Families with babies should pay attention to choosing mosquito repellent products