当前位置:网站首页>Handwritten promise [04] - then method chain call to recognize promise object self return
Handwritten promise [04] - then method chain call to recognize promise object self return
2022-06-11 06:22:00 【Geek student】
Let's look at an example :
let promise = new Promise((resolve, reject) => {
resolve(1000);
})
let p1 = promise.then(value => {
console.log(value);
return p1;
})
p1.then(resolve => {
console.log(resolve);
}, reject => {
console.log(reject);
})
In a situation like this ,p1 Of then It calls itself again Promise object , It's a dead cycle , An error will be reported here .
[TypeError: Chaining cycle detected for promise #<Promise>]
therefore , We will continue to improve Promise Give Way LyPromise It can also report an error when a circular call occurs .
Promise2 Is returned Promise object ,x yes success / Failed callback After the return of Promise object , If the two values are the same, it means that you have returned your own .
therefore , Add a judgment :
function resolvePromise(Promise2, x, resolve, reject) {
if (Promise2 === x) {
return reject(new TypeError("Promise Referenced circularly !!!"))
}
if (x instanceof LyPromise) {
// promise object
x.then(resolve, reject)
} else {
// Common value
resolve(x);
}
}
It is worth noting that ,Promise2 Object is in new LyPromise After execution To get it , But we need to Promise2 stay new Of In the process Just pass it on to resolvePromise function . Obviously, the current code can not meet such requirements , Because you can't get it at this time Promise2.
There is an asynchronous problem here , So we need to use a timer , Give Way new LyPromise This After the process Let's do it again resolvePromise function , You can get Promise2.

Test code :
let promise = new LyPromise((resolve, reject) => {
resolve(1000);
})
let p1 = promise.then(value => {
console.log(value);
return p1;
})
p1.then(resolve => {
console.log(resolve);
}, reject => {
console.log(reject);
})
Running results :
up to now , We have achieved then Method How to judge in chain call Promise Did you return to yourself .
Complete 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) {
setTimeout(() => {
let x = successCallback(this.value);
resolvePromise(Promise2, x, resolve, reject);
}, 0)
} else if (this.status === REJECTED) {
setTimeout(() => {
let x = failCallback(this.reason);
resolvePromise(Promise2, x, resolve, reject)
}, 0)
} 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(promise2, x, resolve, reject) {
if (promise2 === x) {
return reject(new TypeError("Promise Referenced circularly !!!"))
}
if (x instanceof LyPromise) {
// promise object
x.then(resolve, reject)
} else {
// Common value
resolve(x);
}
}
module.exports = LyPromise;
边栏推荐
- Summarize the five most common BlockingQueue features
- Twitter data collection (content, fans, keywords, etc.)
- Devsecops in Agile Environment
- Eureka集群搭建
- FPGA interview notes (III) -- implementation of handshake signal synchronization in cross clock domain, arbitrary frequency division, binary conversion, RAM memory, original code inversion and complem
- jenkins-用户权限管理
- Login and registration based on servlet, JSP and MySQL
- C language war "minesweeping"
- On the social moral and ethical issues behind short videos (personal point of view, for reference only)
- Deployment of Flink
猜你喜欢

修复鼠标右键没有vscode快捷入口的问题

FPGA面試題目筆記(四)—— 序列檢測器、跨時鐘域中的格雷碼、乒乓操作、降低靜動態損耗、定點化無損誤差、恢複時間和移除時間

Installing and using sublist3r in Kali

Vulhub 8.1-backdoor vulnerability recurrence

Using Internet of things technology to accelerate digital transformation

A multi classification model suitable for discrete value classification -- softmax regression

FPGA interview notes (II) -- synchronous asynchronous D flip-flop, static and dynamic timing analysis, frequency division design, retiming

Review XML and JSON

Teach you to write word formula

JIRA software annual summary: release of 12 important functions
随机推荐
Verilog realizes binocular camera image data acquisition and Modelsim simulation, and finally matlab performs image display
Squid agent
修复鼠标右键没有vscode快捷入口的问题
Quantitative understanding (Quantitative deep revolutionary networks for effective information: a whitepaper)
Zvuldrill installation and customs clearance tutorial
On cursor in MySQL
Basic usage of MySQL
Simple understanding of XML and JSON
[must see for game development] 3-step configuration p4ignore + wonderful Q & A analysis (reprinted from user articles)
CCF 2013 12-4 interesting numbers
Docker installation of MySQL and redis
[reading this article is enough!!! Easy to understand] confidence level understanding (95% confidence level and confidence interval)
All the benefits of ci/cd, but greener
FPGA interview notes (II) -- synchronous asynchronous D flip-flop, static and dynamic timing analysis, frequency division design, retiming
Compliance management 101: processes, planning and challenges
FPGA面试题目笔记(一)——FPGA开发流程、亚稳态和竞争冒险、建立保持时间、异步FIFO深度等
Jenkins voucher management
End of 2021 graphics of Shandong University
Invert an array with for
Principle of copyonwritearraylist copy on write