当前位置:网站首页>[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
resolve
And the callback on failurereject
; in addition ,resolve
In addition to normal values , It could be a Promise Instance of object ;reject
The parameter of is usually a Error Instance of object . then
Method returns a new one Promise example , And receive two parametersonResolved(fulfilled Status callback )
;onRejected(rejected Status callback , This parameter is optional )
catch
Method returns a new one Promise examplefinally
No matter what the method is Promise How it will execute , The callback function of this method does not accept any parametersPromise.all
Methods 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 triggerscatch
Method , Will triggerPromise.all()
Methodcatch
Method , If an instance in the parameter itself callscatch
Method , Will not triggerPromise.all()
Methodcatch
MethodPromise.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 producePromise
The 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 parametersthenable
object ( With athen
Method ),Promise.resolve()
Convert the object toPromise
Object and execute immediatelythen
Method ; If the argument is a primitive value , Or one that doesn'tthen
Object of method , bePromise.resolve()
Method returns a new one Promise object , Status asfulfilled
, Its parameters will be used asthen
In the methodonResolved
The parameters of the callback function , IfPromise.resolve()
Method without parameters , Will return directly to afulfilled
State 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);
}
});
});
}
};
边栏推荐
- 数值法求解最优控制问题(一)——梯度法
- IC_EDA_ALL虚拟机(丰富版):questasim、vivado、vcs、verdi、dc、pt、spyglass、icc2、synplify、INCISIVE、IC617、MMSIM、工艺库
- On the practice of performance optimization and stability guarantee
- instanceof
- php安装swoole扩展
- La loi des 10 000 heures ne fait pas de vous un maître de programmation, mais au moins un bon point de départ
- 利用C#实现Pdf转图片
- Chapter 8. MapReduce production experience
- C2338 Cannot format an argument. To make type T formattable provide a formatter<T> specialization:
- Thoughts in Starbucks
猜你喜欢
[classes and objects] explain classes and objects in simple terms
这两种驱蚊成份对宝宝有害,有宝宝的家庭,选购驱蚊产品要注意
SQL implementation merges multiple rows of records into one row
Software testing learning - the next day
远端rostopic的本地rviz调用及显示
The dynamic analysis and calculation of expressions are really delicious for flee
2022-06-23 VGMP-OSPF-域间安全策略-NAT策略(更新中)
Arctic code vault contributor
2022-06-23 VGMP-OSPF-域間安全策略-NAT策略(更新中)
10000小时定律不会让你成为编程大师,但至少是个好的起点
随机推荐
Integration test practice (1) theoretical basis
Code management tools
[C /vb.net] convert PDF to svg/image, svg/image to PDF
【类和对象】深入浅出类和对象
centos php7.3安装redis扩展
【5G NR】UE注册流程
Arctic code vault contributor
How to plan well?
Ruoyi interface permission verification
Golang operation redis: write and read kV data
Golang operation redis: write and read hash type data
Software testing learning - day one
Sorting out the core ideas of the pyramid principle
[LeetCode]404. Sum of left leaves
The dynamic analysis and calculation of expressions are really delicious for flee
熊市里的大机构压力倍增,灰度、Tether、微策略等巨鲸会不会成为'巨雷'?
机械观和系统观的科学思维方式各有什么特点和作用
Daily question brushing record (11)
Derivation of variance iteration formula
[open source project recommendation colugomum] this group of undergraduates open source retail industry solutions based on the domestic deep learning framework paddlepadddle