当前位置:网站首页>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
边栏推荐
- Leetcode dynamic planning training camp (1-5 days)
- Grafana shares links with variable parameters
- Five minutes to show you what JWT is
- Remote code execution in Win 11 using wpad / PAC and JScript 3
- Numpy sort search count set
- SQL Server Connectors By Thread Pool | DTSQLServerTP plugin instructions
- Cadence Orcad Capture 批量更改元件封装功能介绍图文教程及视频演示
- What is the difference between a host and a server?
- R language uses the preprocess function of caret package for data preprocessing: BoxCox transform all data columns (convert non normal distribution data columns to normal distribution data and can not
- [text classification cases] (4) RNN and LSTM film evaluation Tendency Classification, with tensorflow complete code attached
猜你喜欢

Commit and ROLLBACK in DCL of 16mysql
![Es error: request contains unrecognized parameter [ignore_throttled]](/img/17/9131c3eb023b94b3e06b0e1a56a461.png)
Es error: request contains unrecognized parameter [ignore_throttled]

What is the difference between a host and a server?

考研英语唐叔的语法课笔记

JDBC tool class jdbcfiledateutil uploads files and date format conversion, including the latest, simplest and easiest way to upload single files and multiple files

Understanding various team patterns in scrum patterns

LeetCode动态规划训练营(1~5天)

Fundamentals of network communication (LAN, Wan, IP address, port number, protocol, encapsulation and distribution)

How to create bep-20 pass on BNB chain

Unity general steps for creating a hyper realistic 3D scene
随机推荐
Operation of numpy array
Confusion about thread blocking after calling the read () method of wrapper flow
What is the difference between a host and a server?
PCL点云处理之直线与平面的交点计算(五十三)
Mysql database - connection query
R language survival package coxph function to build Cox regression model, ggrisk package ggrisk function and two_ Scatter function visualizes the risk score map of Cox regression, interprets the risk
An error is reported in the initialization metadata of the dolphin scheduler -- it turns out that there is a special symbol in the password. "$“
selenium. common. exceptions. WebDriverException: Message: ‘chromedriver‘ executable needs to be in PAT
波场DAO新物种下场,USDD如何破局稳定币市场?
使用 WPAD/PAC 和 JScript在win11中进行远程代码执行
PCA based geometric feature calculation of PCL point cloud processing (52)
How does onlyoffice solve no route to host
Still using listview? Use animatedlist to make list elements move
【2022】将3D目标检测看作序列预测-Point2Seq: Detecting 3D Objects as Sequences
Sqoop imports tinyint type fields to boolean type
R语言ggplot2可视化分面图(facet_wrap)、使用lineheight参数自定义设置分面图标签栏(灰色标签栏)的高度
Handwritten Google's first generation distributed computing framework MapReduce
Why does ES6 need to introduce map when JS already has object type
ArcGIS js api 4. X submergence analysis and water submergence analysis
SQL Server Connectors By Thread Pool | DTSQLServerTP plugin instructions