当前位置:网站首页>[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);
}
});
});
}
};
边栏推荐
- Tool class static method calls @autowired injected service
- Yolov3 learning notes
- Modify MySQL password
- Software testing assignment - day 1
- Getting started with pytest
- centos php7.2.24升级到php7.3
- Error c2017: illegal escape sequence
- Selenium - by changing the window size, the width, height and length of different models will be different
- The list of "I'm crazy about open source" was released in the first week, with 160 developers on the list
- [Code] if (list! = null & list. Size() > 0) optimization, set empty judgment implementation method
猜你喜欢
每日刷題記錄 (十一)
Yolov2 learning and summary
golang操作redis:写入、读取kv数据
[classes and objects] explain classes and objects in simple terms
Yolov1 learning notes
这两种驱蚊成份对宝宝有害,有宝宝的家庭,选购驱蚊产品要注意
Asynchronous programming: async/await in asp Net
Machine learning | simple but feature standardization methods that can improve the effect of the model (comparison and analysis of robustscaler, minmaxscaler, standardscaler)
【开源项目推荐-ColugoMum】这群本科生基于国产深度学习框架PaddlePadddle开源了零售行业解决方案
Summary of remote connection of MySQL
随机推荐
多个全局异常处理类,怎么规定执行顺序
How matlab modifies default settings
Dbnet: real time scene text detection with differentiable binarization
【code】偶尔取值、判空、查表、验证等
服务器如何设置多界面和装IIS呢?甜甜给你解答!
2022 East China Normal University postgraduate entrance examination machine test questions - detailed solution
这两种驱蚊成份对宝宝有害,有宝宝的家庭,选购驱蚊产品要注意
Pytest -- write and manage test cases
修改MySQL密码
[untitled] 5 self use history
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'?
Code management tools
golang操作redis:写入、读取hash类型数据
centos php7.2.24升级到php7.3
Know flex box
[untitled] 8 simplified address book
远端rostopic的本地rviz调用及显示
Software testing learning - day one
dataworks自定义函数开发环境搭建
VMware virtual machine C disk expansion