当前位置:网站首页>Handwriting promise [03] - realize multiple calls and chain calls of then method
Handwriting promise [03] - realize multiple calls and chain calls of then method
2022-06-11 06:22:00 【Geek student】
1. then Multiple calls to method
We are defining success successCallback And failure failCallback When you call back , Only one value is defined , Not considered then Method is called more than once asynchronously , Therefore, successful and failed callbacks should be defined as a thing that can hold multiple values – Array .
successCallback = [];
failCallback = [];
therefore then The callback store in the method also changes :
this.successCallback.push(successCallback);
this.failCallback.push(failCallback);
up to now , Multiple callback functions have already existed successfully / The failure of the Array of callback functions It's in , When the status changes to success / In case of failure, each item in the callback function array should be called in turn , therefore resolve/reject Should read :
resolve = value => {
if (this.status !== PENDING) return;
this.status = FULFILLED;
this.value = value;
while (this.successCallback.length) {
// The first item of the array should be executed first , And the first item of the array is the callback function required, so you can directly call
this.successCallBack.shift()(this.value);
}
}
reject = value => {
if (this.status !== PENDING) return;
this.status = REJECTED;
this.reason = reason;
while (this.failCallback.length) {
// Empathy resolve
this.failCallback.shift()(this.reason);
}
}
Promise in then Method can be called more than once .
2. then Chain call to method
promise.then().then().then()
2.1 Yes then Method
thenThe method isPromiseMedium .thenMethod can be called in a chain , explainthenThe return value of the method is aPromiseobject .
// since then Method returns a Promise object , Then create a Promise Object to return
then(successCallback, failCallback) {
let Promise2 = new LyPromise(() => {
if (this.status === FULFILLED) {
successCallback(this.value);
} else if (this.status === REJECTED) {
failCallback(this.reason);
}
});
return Promise2;
};
such ,then Just go back to one Promise Objects can be given to Of the next call then 了 .
Now? , We need to consider next then Method How to get this By previous then Back to Promise object .
then(successCallback, failCallback) {
let Promise2 = new LyPromise((resolve, reject) => {
// When successful / You can achieve this success when you fail / Failed callback , So you can also get the return value of this here
if (this.status === FULFILLED) {
// This x Is the return value of this successful callback
let x = successCallback(this.value);
resolve(x);
} else if (this.status === REJECTED) {
let x = failCallback(this.reason);
reject(x);
}
});
return Promise2;
};
such then Method can return a Promise Object .
however , If the return value is a Promise What about the object ?
therefore , What needs to be done next is : Judge x The value of is Common value still Promise object ;
- If it is
Common valuedirectresolve; - If it is
Promiseobject , According toPromiseObject to determine the use ofresolvestillreject;
// Write a function here to facilitate reuse
function resolvePromise(x, resolve, reject) {
// Q: How to judge this x Is it a Promise object
// A: Judge x Is it right? LyPromise An instance object of
if (x instanceof LyPromise) {
x.then(resolve, reject);
} else {
resolve(x);
}
}
Check x Is it a Promise The object is written .
2.2 then Method
then(successCallback, failCallback) {
let Promise2 = new LyPromise((resolve, reject) => {
if (this.status === FULFILLED) {
let x = successCallback(this.value);
resolvePromise(x, resolve, reject);
} else if (this.status === REJECTED) {
let x = failCallback(this.reason);
resolvePromise(x, resolve, reject);
} else {
this.successCallback.push(successCallback);
this.failCallback.push(failCallback);
}
})
return Promise2;
}
3. Implemented so far Promise Code
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
class LyPromise {
constructor(executor) {
executor(this.resolve, this.reject)
}
status = PENDING;
value = undefined;
reason = undefined;
// Successful callback
successCallback = [];
// Failed callback
failCallback = [];
resolve = (value) => {
if (this.status !== PENDING) return;
this.status = FULFILLED;
this.value = value;
// Determine whether a successful callback exists , If there is Call the successful callback
// this.successCallback && this.successCallback(this.value);
while (this.successCallback.length) {
this.successCallback.shift()(this.value); // perform
}
}
reject = (reason) => {
if (this.status !== PENDING) return;
this.status = REJECTED;
this.reason = reason;
// Determine whether the failed callback exists , If there is Call the failed callback
// this.failCallback && this.failCallback(this.reason)
while (this.failCallback.length) {
this.failCallback.shift()(this.reason)
}
}
then(successCallback, failCallback) {
let Promise2 = new LyPromise((resolve, reject) => {
if (this.status === FULFILLED) {
let x = successCallback(this.value);
resolvePromise(x, resolve, reject);
} else if (this.status === REJECTED) {
let x = failCallback(this.reason);
resolvePromise(x, resolve, reject)
} else {
// When the actuator operates asynchronously ,status still pending,
// So at this time, we don't know whether it is a success or a failure callback , So here we need to call back these two
// Store it
this.successCallback.push(successCallback);
this.failCallback.push(failCallback);
}
})
return Promise2;
}
}
function resolvePromise(x, resolve, reject) {
if (x instanceof LyPromise) {
// promise object
x.then(resolve, reject)
} else {
// Common value
resolve(x);
}
}
module.exports = LyPromise;
边栏推荐
- On the social moral and ethical issues behind short videos (personal point of view, for reference only)
- Simple understanding of pseudo elements before and after
- Completabilefuture asynchronous task choreography usage and explanation
- ijkPlayer中的错误码
- Jenkins voucher management
- Box model
- Use meshlab to sample the point cloud of CAD model and display it in PCL
- MySQL implements over partition by (sorting the data in the group after grouping)
- Compliance management 101: processes, planning and challenges
- LeetCodeT526
猜你喜欢

Build the first power cloud platform

Summarize the five most common BlockingQueue features

Vulhub 8.1-backdoor vulnerability recurrence

Sentinel annotation support - @sentinelresource usage details

MMEditing中超分模型训练与测试

Record the first data preprocessing process

Servlet

SQLI_ LIBS range construction and 1-10get injection practice

Super details to teach you how to use Jenkins to realize automatic jar package deployment

Do you know the functions of getbit and setbit in redis?
随机推荐
A collection of problems on improving working frequency and reducing power consumption in FPGA design
Summarize the five most common BlockingQueue features
Chapter 6 of machine learning [series] random forest model
Vulnhub's breach1.0 range exercise
Wechat applet (authorized login) (not recommended, click the home page to view the updated authorized login)
Excellent practice | how to avoid a bloody case caused by a line of wrong code?
Eureka集群搭建
Sqli-libs range 23-24 filtration and secondary injection practice
Learn a trick to use MySQL functions to realize data desensitization
CCF 2013 12-5 I‘m stuck
How to use perforce helix core with CI build server
Shuffleerror:error in shuffle in fetcher solution
Super explanation
Principle of copyonwritearraylist copy on write
Installing MySQL for Linux
Instanceof and type conversion
End of 2021 graphics of Shandong University
Basic usage of MySQL
Build the first power cloud platform
PgSQL reports an error: current transaction is aborted, commands ignored until end of transaction block