当前位置:网站首页>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
边栏推荐
- How about CICC fortune? Is it safe to open an account
- Leetcode XOR operation
- R语言ggplot2可视化:ggplot2可视化散点图并使用geom_mark_ellipse函数在数据簇或数据分组的数据点周围添加椭圆进行注释
- [talkative cloud native] load balancing - the passenger flow of small restaurants has increased
- Mysql database and table building: the difference between utf8 and utf8mb4
- Rédaction de thèses 19: différences entre les thèses de conférence et les thèses périodiques
- 【2022】将3D目标检测看作序列预测-Point2Seq: Detecting 3D Objects as Sequences
- WordPress插件:WP-China-Yes解决国内访问官网慢的方法
- [numerical prediction case] (3) LSTM time series electricity quantity prediction, with tensorflow complete code attached
- Database query - course selection system
猜你喜欢

Computing the intersection of two planes in PCL point cloud processing (51)

16MySQL之DCL 中 COMMIT和ROllBACK

16MySQL之DCL 中 COMMIT和ROllBACK

Sqoop imports tinyint type fields to boolean type

Five minutes to show you what JWT is

Building googlenet neural network based on pytorch for flower recognition

CVPR 2022 | querydet: use cascaded sparse query to accelerate small target detection under high resolution

After route link navigation, the sub page does not display the navigation style problem

STM32 Basics

Servlet learning notes
随机推荐
[target tracking] pedestrian attitude recognition based on frame difference method combined with Kalman filter, with matlab code
本地调用feign接口报404
PostgreSQL basic functions
LeetCode异或运算
STM32基础知识
SQL Server Connectors By Thread Pool | DTSQLServerTP plugin instructions
NC basic usage 2
Rédaction de thèses 19: différences entre les thèses de conférence et les thèses périodiques
JDBC tool class jdbcconutil gets the connection to the database
如何做产品创新?——产品创新方法论探索一
Alicloud: could not connect to SMTP host: SMTP 163.com, port: 25
CVPR 2022 | QueryDet:使用级联稀疏query加速高分辨率下的小目标检测
微信中金财富高端专区安全吗,证券如何开户呢
Still using listview? Use animatedlist to make list elements move
Database query - course selection system
Cadence Orcad Capture CIS更换元器件之Link Database 功能介绍图文教程及视频演示
PCL点云处理之直线与平面的交点计算(五十三)
Remote code execution in Win 11 using wpad / PAC and JScript 1
PCA based geometric feature calculation of PCL point cloud processing (52)
An error is reported when sqoop imports data from Mysql to HDFS: sqlexception in nextkeyvalue