当前位置:网站首页>Implementation of mypromise
Implementation of mypromise
2022-04-23 20:19:00 【wytraining】
1. Achieve one MyPromise
function resolvePromise(promise2,x,resolve,reject){
// Judge x Is it right? promise
// The specification States : We allow others to scribble , This code can realize our promise And other people's promise Interact
if(promise2 === x){// You can't wait for yourself to finish
return reject(new TypeError(' Circular reference '));
}
// x Yes, except for null Objects or functions other than
if(x !=null && (typeof x === 'object' || typeof x === 'function')){
let called;// Failure to prevent base note from successful call
try{// Prevent taking then Is there an exception object.defineProperty
let then = x.then;// take x Of then Method {then:{}}
if(typeof then === 'function'){// If then If it's a function, you think it's a function promise
//call The first parameter is this, Followed by successful callbacks and failed callbacks
then.call(x,y => {// If Y yes promise Just continue recursion promise
if(called) return;
called = true;
resolvePromise(promise2,y,resolve,reject)
},r => { // As long as you fail, you fail
if(called) return;
called = true;
reject(r);
});
}else{//then It's a common object , Just succeed directly
resolve(x);
}
}catch (e){
if(called) return;
called = true;
reject(e)
}
}else{//x = 123 x Is a normal value As the next then Successful parameters
resolve(x)
}
}
class MyPromise {
constructor (executor){
// The default state is waiting
this.status = 'pending';
this.value = undefined;
this.reason = undefined;
// Save successful callbacks
this.onResolvedCallbacks = [];
// Save failed callbacks
this.onRejectedCallbacks = [];
let resolve = (data) => {//this It's an example
if(this.status === 'pending'){
this.value = data;
this.status = "resolved";
this.onResolvedCallbacks.forEach(fn => fn());
}
}
let reject = (reason) => {
if(this.status === 'pending'){
this.reason = reason;
this.status = 'rejected';
this.onRejectedCallbacks.forEach(fn => fn());
}
}
try{// Exceptions may occur during execution
executor(resolve,reject);
}catch (e){
reject(e);//promise failed
}
}
then(onFuiFilled,onRejected){
// Prevent penetration
onFuiFilled = typeof onFuiFilled === 'function' ? onFuiFilled : y => y;
onRejected = typeof onRejected === 'function' ? onRejected :err => {throw err;}
let promise2;// For the next time then Methodical promise
if(this.status === 'resolved'){
promise2 = new MyPromise((resolve,reject) => {
setTimeout(() => {
try{
// The logic of success The logic of failure
let x = onFuiFilled(this.value);
// see x Is it right? promise If it is promise Take his results As promise2 The result of success
// If you return a normal value , As promise2 Successful results
//resolvePromise Can be parsed x and promise2 The relationship between
// stay resolvePromise Pass in four parameters , The first is the return promise, The second is the result returned , The third and fourth are resolve() and reject() Methods .
resolvePromise(promise2,x,resolve,reject)
}catch(e){
reject(e);
}
},0)
});
}
if(this.status === 'rejected'){
promise2 = new MyPromise((resolve,reject) => {
setTimeout(() => {
try{
let x = onRejected(this.reason);
// stay resolvePromise Pass in four parameters , The first is the return promise, The second is the result returned , The third and fourth are resolve() and reject() Methods .
resolvePromise(promise2,x,resolve,reject)
}catch(e){
reject(e);
}
},0)
});
}
// There is neither completion nor failure at present
if(this.status === 'pending'){
promise2 = new MyPromise((resolve,reject) => {
// Store the successful functions one by one in the successful callback function array
this.onResolvedCallbacks.push( () =>{
setTimeout(() => {
try{
let x = onFuiFilled(this.value);
resolvePromise(promise2,x,resolve,reject);
}catch(e){
reject(e);
}
},0)
});
// Store the failed functions one by one in the failed callback function array
this.onRejectedCallbacks.push( ()=>{
setTimeout(() => {
try{
let x = onRejected(this.reason);
resolvePromise(promise2,x,resolve,reject)
}catch(e){
reject(e)
}
},0)
})
})
}
return promise2;// call then Then return to a new promise
}
catch (onRejected) {
// catch The way is then There is no shorthand for success
return this.then(null, onRejected);
}
}
MyPromise.all = function (promises) {
//promises It's a promise Array of
return new MyPromise(function (resolve, reject) {
let arr = []; //arr Is the result of the final return value
let i = 0; // Indicates how many times you have succeeded
function processData(index, data) {
arr[index] = data;
if (++i === promises.length) {
resolve(arr);
}
}
for (let i = 0; i < promises.length; i++) {
promises[i].then(function (data) {
processData(i, data)
}, reject)
}
})
}
// As long as there is one promise succeed Even if it succeeds . If the first one fails, it fails
MyPromise.race = function (promises) {
return new MyPromise((resolve, reject) => {
for (var i = 0; i < promises.length; i++) {
promises[i].then(resolve,reject)
}
})
}
// Generate a successful promise
MyPromise.resolve = function(value){
return new MyPromise((resolve,reject) => resolve(value));
}
// Generate a failed promise
MyPromise.reject = function(reason){
return new MyPromise((resolve,reject) => reject(reason));
}
MyPromise.defer = MyPromise.deferred = function () {
let dfd = {};
dfd.MyPromise = new MyPromise( (resolve, reject) => {
dfd.resolve = resolve;
dfd.reject = reject;
});
return dfd
}
2. call
let p = new MyPromise((resolve, reject)=>{
setTimeout(()=>{
console.log('ok')
resolve(' success ')
}, 2000)
})
p.then(data=>{
console.log(data)
})
Promise Can't ?? Look here !!! The most accessible thing in history Promise!!!
版权声明
本文为[wytraining]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210552098072.html
边栏推荐
- DNS cloud school | analysis of hidden tunnel attacks in the hidden corner of DNS
- Linux64Bit下安装MySQL5.6-不能修改root密码
- SQL Server connectors by thread pool 𞓜 instructions for dtsqlservertp plug-in
- Fundamentals of network communication (LAN, Wan, IP address, port number, protocol, encapsulation and distribution)
- R language ggplot2 visualization: ggplot2 visualizes the scatter diagram and uses geom_ mark_ The ellipse function adds ellipses around data points of data clusters or data groups for annotation
- 程序设计语言基础(2)
- Vericrypt file hard disk encryption tutorial
- CVPR 2022 | QueryDet:使用级联稀疏query加速高分辨率下的小目标检测
- SQL Server Connectors By Thread Pool | DTSQLServerTP plugin instructions
- The R language uses the timeroc package to calculate the multi time AUC value of survival data without competitive risk, and uses the confint function to calculate the confidence interval value of mul
猜你喜欢
SQL Server connectors by thread pool 𞓜 instructions for dtsqlservertp plug-in
WordPress插件:WP-China-Yes解决国内访问官网慢的方法
What is the difference between a host and a server?
山东大学软件学院项目实训-创新实训-网络安全靶场实验平台(八)
Openharmony open source developer growth plan, looking for new open source forces that change the world!
STM32 Basics
Numpy mathematical function & logical function
CVPR 2022 | querydet: use cascaded sparse query to accelerate small target detection under high resolution
Click an EL checkbox to select all questions
Unity general steps for creating a hyper realistic 3D scene
随机推荐
After route link navigation, the sub page does not display the navigation style problem
Cadence OrCAD capture batch change component packaging function introduction graphic tutorial and video demonstration
CVPR 2022 | querydet: use cascaded sparse query to accelerate small target detection under high resolution
Confusion about thread blocking after calling the read () method of wrapper flow
NC basic usage 3
论文写作 19: 会议论文与期刊论文的区别
The textarea cursor cannot be controlled by the keyboard due to antd dropdown + modal + textarea
Compact CUDA tutorial - CUDA driver API
R语言survival包coxph函数构建cox回归模型、ggrisk包ggrisk函数和two_scatter函数可视化Cox回归的风险评分图、解读风险评分图、基于LIRI数据集(基因数据集)
Error reported by Azkaban: Azkaban jobExecutor. utils. process. ProcessFailureException: Process exited with code 127
Zdns was invited to attend the annual conference of Tencent cloud basic resources and share the 2020 domain name industry development report
AQS learning
Numpy - creation of data type and array
考研英语唐叔的语法课笔记
SQL Server Connectors By Thread Pool | DTSQLServerTP plugin instructions
Historical track data reading of Holux m1200-e Bluetooth GPS track recorder
使用 WPAD/PAC 和 JScript在win11中进行远程代码执行1
Cadence Orcad Capture CIS更换元器件之Link Database 功能介绍图文教程及视频演示
Mysql database - single table query (III)
WordPress插件:WP-China-Yes解决国内访问官网慢的方法