当前位置:网站首页>Promise from getting started to mastering (Chapter 3: customize (handwriting) promise)
Promise from getting started to mastering (Chapter 3: customize (handwriting) promise)
2022-07-28 02:13:00 【Ruoshui CJJ】
Promise From entry to mastery ( The first 3 Chapter Handwriting Promise)
- The first 3 Chapter Customize ( Handwriting )Promise
- 3.1 build Promise The initial structure
- 3.2 resolve and reject Structure building
- 3.3 resolve and reject Code implementation
- 3.4 throw Throw an exception to change the State
- 3.5 Promise Object state can only be modified once
- 3.6 then Method to execute the callback
- 3.7 Callback execution of asynchronous tasks
- 3.8 Specify the implementation of multiple callback functions
- 3.9 Synchronous modification status then Returns the result of the
- 3.10 Asynchronous modification state then Returns the result of the
- 3.12 then Improvement and optimization of methods
- 3.13 catch Method exception penetration and value passing
- 3.14 Promise Encapsulation of methods in (resolve, reject, race, all)
- 3.15 Promise Complete implementation
- 3.16 class Version implementation
The first 3 Chapter Customize ( Handwriting )Promise
3.1 build Promise The initial structure
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Promise encapsulation - Initial structure construction </title>
<!-- introduce promise.js To cover the original Promise -->
<script src="./promise.js"></script>
</head>
<body>
<script> let p = new Promise((resolve, reject)=>{
resolve("ok") }); p.then(value=>{
console.log(value); },reason=>{
console.log(reason); }); </script>
</body>
</html>
function Promise(executor){
}
// add to then Method
Promise.prototype.then = function(onResolved, onRejected){
}
3.2 resolve and reject Structure building
function Promise(executor){
// because resolve and reject When used, it is a function , So define two functions
function resolve(data){
}
function reject(data){
}
// The executor function is called synchronously internally , Directly take it and add a bracket behind it to synchronously call
executor();
}
// add to then Method
Promise.prototype.then = function(onResolved, onRejected){
}
3.3 resolve and reject Code implementation
// Declaration constructor
function Promise(executor) {
// Add attribute
this.PromiseState = 'pending';
this.PromiseResult = null;
// Save the this value
const self = this;
// because resolve and reject When used, it is a function , So define two functions
function resolve(data) {
// 1. Modify the state of the object (PromiseState)
self.PromiseState = 'fulfilled';
// 2. Set the result value of the object (PromiseResult)
self.PromiseResult = data;
};
function reject(data) {
// 1. Modify the state of the object (PromiseState)
self.PromiseState = 'rejected';
// 2. Set the result value of the object (PromiseResult)
self.PromiseResult = data;
}
// The executor function is called synchronously internally , Directly take it and add a bracket behind it to synchronously call
executor(resolve, reject);
}
// add to then Method
Promise.prototype.then = function (onResolved, onRejected) {
}
3.4 throw Throw an exception to change the State
// Declaration constructor
function Promise(executor) {
// Add attribute
this.PromiseState = 'pending';
this.PromiseResult = null;
// Save the this value
const self = this;
// because resolve and reject When used, it is a function , So define two functions
function resolve(data) {
// 1. Modify the state of the object (PromiseState)
self.PromiseState = 'fulfilled';
// 2. Set the result value of the object (PromiseResult)
self.PromiseResult = data;
};
function reject(data) {
// 1. Modify the state of the object (PromiseState)
self.PromiseState = 'rejected';
// 2. Set the result value of the object (PromiseResult)
self.PromiseResult = data;
}
// The executor function is called synchronously internally , Directly take it and add a bracket behind it to synchronously call
try{
executor(resolve, reject);
}catch(e){
reject(e);
}
}
// add to then Method
Promise.prototype.then = function (onResolved, onRejected) {
}
3.5 Promise Object state can only be modified once
// Declaration constructor
function Promise(executor) {
// Add attribute
this.PromiseState = 'pending';
this.PromiseResult = null;
// Save the this value
const self = this;
// because resolve and reject When used, it is a function , So define two functions
function resolve(data) {
// If the object state is not pending, Then go straight back , Do not execute the following code
if(self.PromiseState !== 'pending') return;
// 1. Modify the state of the object (PromiseState)
self.PromiseState = 'fulfilled';
// 2. Set the result value of the object (PromiseResult)
self.PromiseResult = data;
};
function reject(data) {
// If the object state is not pending, Then go straight back , Do not execute the following code
if(self.PromiseState !== 'pending') return;
// 1. Modify the state of the object (PromiseState)
self.PromiseState = 'rejected';
// 2. Set the result value of the object (PromiseResult)
self.PromiseResult = data;
}
// The executor function is called synchronously internally , Directly take it and add a bracket behind it to synchronously call
try{
executor(resolve, reject);
}catch(e){
reject(e);
}
}
// add to then Method
Promise.prototype.then = function (onResolved, onRejected) {
}
3.6 then Method to execute the callback
// Declaration constructor
function Promise(executor) {
// Add attribute
this.PromiseState = 'pending';
this.PromiseResult = null;
// Save the this value
const self = this;
// because resolve and reject When used, it is a function , So define two functions
function resolve(data) {
// If the object state is not pending, Then go straight back , Do not execute the following code
if(self.PromiseState !== 'pending') return;
// 1. Modify the state of the object (PromiseState)
self.PromiseState = 'fulfilled';
// 2. Set the result value of the object (PromiseResult)
self.PromiseResult = data;
};
function reject(data) {
// If the object state is not pending, Then go straight back , Do not execute the following code
if(self.PromiseState !== 'pending') return;
// 1. Modify the state of the object (PromiseState)
self.PromiseState = 'rejected';
// 2. Set the result value of the object (PromiseResult)
self.PromiseResult = data;
}
// The executor function is called synchronously internally , Directly take it and add a bracket behind it to synchronously call
try{
executor(resolve, reject);
}catch(e){
reject(e);
}
}
// add to then Method
Promise.prototype.then = function (onResolved, onRejected) {
// because then The method is Promise Instance object of p Called , So here's this It's the object p, It can be done by this.PromiseState Get the status of the object
if(this.PromiseState === 'fulfilled'){
onResolved(this.PromiseResult);
}
if(this.PromiseState === 'rejected'){
onRejected(this.PromiseResult);
}
}
3.7 Callback execution of asynchronous tasks
This way of saving callbacks is flawed , Not suitable for chain call then Method
// Declaration constructor
function Promise(executor) {
// Add attribute
this.PromiseState = 'pending';
this.PromiseResult = null;
// Save the this value
const self = this;
// preservation then The callback function in
this.callback = {
};
// because resolve and reject When used, it is a function , So define two functions
function resolve(data) {
// If the object state is not pending, Then go straight back , Do not execute the following code
if(self.PromiseState !== 'pending') return;
// 1. Modify the state of the object (PromiseState)
self.PromiseState = 'fulfilled';
// 2. Set the result value of the object (PromiseResult)
self.PromiseResult = data;
// Check the callback after the asynchronous task ends , And execute the successful callback function
if(self.callback.onResolved){
self.callback.onResolved(data);
}
};
function reject(data) {
// If the object state is not pending, Then go straight back , Do not execute the following code
if(self.PromiseState !== 'pending') return;
// 1. Modify the state of the object (PromiseState)
self.PromiseState = 'rejected';
// 2. Set the result value of the object (PromiseResult)
self.PromiseResult = data;
// Check the callback after the asynchronous task ends , And execute the failed callback function
if(self.callback.onRejected){
self.callback.onRejected(data);
}
}
// The executor function is called synchronously internally , Directly take it and add a bracket behind it to synchronously call
try{
executor(resolve, reject);
}catch(e){
reject(e);
}
}
// add to then Method
Promise.prototype.then = function (onResolved, onRejected) {
// because then The method is Promise Instance object of p Called , So here's this It's the object p, It can be done by this.PromiseState Get the status of the object
if(this.PromiseState === 'fulfilled'){
onResolved(this.PromiseResult);
}
if(this.PromiseState === 'rejected'){
onRejected(this.PromiseResult);
}
// If Promise There are asynchronous tasks in , So you need to then Save the callback function in , Wait for the asynchronous task to finish , After the change Promise And then execute then The callback function in
if(this.PromiseState === 'pending'){
this.callback = {
onResolved:onResolved,
onRejected:onRejected
}
}
}
3.8 Specify the implementation of multiple callback functions

// Declaration constructor
function Promise(executor) {
// Add attribute
this.PromiseState = 'pending';
this.PromiseResult = null;
// Save the this value
const self = this;
// preservation then The callback function in
this.callbacks = [];
// because resolve and reject When used, it is a function , So define two functions
function resolve(data) {
// If the object state is not pending, Then go straight back , Do not execute the following code
if(self.PromiseState !== 'pending') return;
// 1. Modify the state of the object (PromiseState)
self.PromiseState = 'fulfilled';
// 2. Set the result value of the object (PromiseResult)
self.PromiseResult = data;
// After the asynchronous task ends, execute all successful callback functions one by one
self.callbacks.forEach(element => {
element.onResolved(data)
});
};
function reject(data) {
// If the object state is not pending, Then go straight back , Do not execute the following code
if(self.PromiseState !== 'pending') return;
// 1. Modify the state of the object (PromiseState)
self.PromiseState = 'rejected';
// 2. Set the result value of the object (PromiseResult)
self.PromiseResult = data;
// After the asynchronous task ends, execute the failed callback functions one by one
self.callbacks.forEach(element=>{
element.onRejected(data)
})
}
// The executor function is called synchronously internally , Directly take it and add a bracket behind it to synchronously call
try{
executor(resolve, reject);
}catch(e){
reject(e);
}
}
// add to then Method
Promise.prototype.then = function (onResolved, onRejected) {
// because then The method is Promise Instance object of p Called , So here's this It's the object p, It can be done by this.PromiseState Get the status of the object
if(this.PromiseState === 'fulfilled'){
onResolved(this.PromiseResult);
}
if(this.PromiseState === 'rejected'){
onRejected(this.PromiseResult);
}
// If Promise There are asynchronous tasks in , So you need to then Save the callback function in ,
// Wait for the asynchronous task to finish , After the change Promise And then execute then The callback function in
if(this.PromiseState === 'pending'){
this.callbacks.push({
onResolved:onResolved,
onRejected:onRejected
})
}
}
3.9 Synchronous modification status then Returns the result of the

3.10 Asynchronous modification state then Returns the result of the
because Promise The tasks contained in are asynchronous , So when p call then When the method is used ,Promise It's not changed yet , Still in its initial state pending, So in then The third condition of judgment will be satisfied inside the method this.PromiseState === ‘pending’, Inside this judgment is to then Add the callback function of callbacks in , stay Promise After the state of changes, execute the corresponding successful or failed callback methods ,
If the synchronization task succeeds , Then it will execute then Medium onResolved Method , The result of this method is determined by the result of its callback function , If the callback function returns a Promise, So this Promise The result of the decision onResolved Result of method , If the callback function returns other values , Such as a string ,undefined, So return resolve
// Declaration constructor
function Promise(executor) {
// Add attribute
this.PromiseState = 'pending';
this.PromiseResult = null;
// Save the this value
const self = this;
// preservation then The callback function in
this.callbacks = [];
// because resolve and reject When used, it is a function , So define two functions
function resolve(data) {
// If the object state is not pending, Then go straight back , Do not execute the following code
if (self.PromiseState !== 'pending') return;
// 1. Modify the state of the object (PromiseState)
self.PromiseState = 'fulfilled';
// 2. Set the result value of the object (PromiseResult)
self.PromiseResult = data;
// After the asynchronous task ends, execute all successful callback functions one by one
self.callbacks.forEach(element => {
element.onResolved(data)
});
};
function reject(data) {
// If the object state is not pending, Then go straight back , Do not execute the following code
if (self.PromiseState !== 'pending') return;
// 1. Modify the state of the object (PromiseState)
self.PromiseState = 'rejected';
// 2. Set the result value of the object (PromiseResult)
self.PromiseResult = data;
// After the asynchronous task ends, execute the failed callback functions one by one
self.callbacks.forEach(element => {
element.onRejected(data)
})
}
// The executor function is called synchronously internally , Directly take it and add a bracket behind it to synchronously call
try {
executor(resolve, reject);
} catch (e) {
reject(e);
}
}
// add to then Method
Promise.prototype.then = function (onResolved, onRejected) {
const self = this;
return new Promise((resolve, reject) => {
if (this.PromiseState === 'fulfilled') {
try {
let res = onResolved(this.PromiseResult);
if (res instanceof Promise) {
console.log(" Go here ")
res.then(v => {
resolve(v);
}, r => {
reject(r);
})
} else {
resolve(res)
}
} catch (e) {
reject(e)
}
}
if (this.PromiseState === 'rejected') {
onRejected(this.PromiseResult);
}
if (this.PromiseState === 'pending') {
this.callbacks.push({
onResolved: function () {
try {
let res = onResolved(self.PromiseResult);
if (res instanceof Promise) {
res.then(v => {
resolve(v)
}, r => {
reject(r)
});
} else {
resolve(res)
}
} catch (error) {
reject(error)
}
},
onRejected: function () {
try {
let res = onRejected(self.PromiseResult);
if (res instanceof Promise) {
res.then(v => {
resolve(v)
}, r => {
reject(r)
});
} else {
resolve(res)
}
} catch (error) {
reject(error)
}
}
})
}
});
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Promise encapsulation - Initial structure construction </title>
<!-- introduce promise.js To cover the original Promise -->
<script src="./promise.js"></script>
</head>
<body>
<script> let p = new Promise((resolve, reject)=>{
setTimeout(()=>{
resolve("ok"); }, 1000) }); console.log('p:',p) const result = p.then(value=>{
// return new Promise((resolve, reject)=>{
// resolve("ok"); // }) // console.log(value); throw "err"; },reason=>{
console.log(reason); }); console.log(result); // p.then(value=>{
// console.log(value); // },reason=>{
// console.log(reason); // }); </script>
</body>
</html>
3.12 then Improvement and optimization of methods

Optimized full version :
// Declaration constructor
function Promise(executor) {
// Add attribute
this.PromiseState = 'pending';
this.PromiseResult = null;
// Save the this value
const self = this;
// preservation then The callback function in
this.callbacks = [];
// because resolve and reject When used, it is a function , So define two functions
function resolve(data) {
// If the object state is not pending, Then go straight back , Do not execute the following code
if (self.PromiseState !== 'pending') return;
// 1. Modify the state of the object (PromiseState)
self.PromiseState = 'fulfilled';
// 2. Set the result value of the object (PromiseResult)
self.PromiseResult = data;
// After the asynchronous task ends, execute all successful callback functions one by one
self.callbacks.forEach(element => {
element.onResolved(data)
});
};
function reject(data) {
// If the object state is not pending, Then go straight back , Do not execute the following code
if (self.PromiseState !== 'pending') return;
// 1. Modify the state of the object (PromiseState)
self.PromiseState = 'rejected';
// 2. Set the result value of the object (PromiseResult)
self.PromiseResult = data;
// After the asynchronous task ends, execute the failed callback functions one by one
self.callbacks.forEach(element => {
element.onRejected(data)
})
}
// The executor function is called synchronously internally , Directly take it and add a bracket behind it to synchronously call
try {
executor(resolve, reject);
} catch (e) {
reject(e);
}
}
// add to then Method
Promise.prototype.then = function (onResolved, onRejected) {
const self = this;
return new Promise((resolve, reject) => {
// Packaging function
function callBack(type) {
try {
let res = type(self.PromiseResult);
if (res instanceof Promise) {
res.then(v => {
resolve(v);
}, r => {
reject(r);
})
} else {
resolve(res)
}
} catch (e) {
reject(e)
}
}
if (this.PromiseState === 'fulfilled') {
callBack(onResolved);
}
if (this.PromiseState === 'rejected') {
callBack(onRejected);
}
// Judge pending function
if (this.PromiseState === 'pending') {
this.callbacks.push({
onResolved: function () {
callBack(onResolved);
},
onRejected: function () {
callBack(onRejected);
}
})
}
});
}
3.13 catch Method exception penetration and value passing


// Declaration constructor
function Promise(executor) {
// Add attribute
this.PromiseState = 'pending';
this.PromiseResult = null;
// Save the this value
const self = this;
// preservation then The callback function in
this.callbacks = [];
// because resolve and reject When used, it is a function , So define two functions
function resolve(data) {
// If the object state is not pending, Then go straight back , Do not execute the following code
if (self.PromiseState !== 'pending') return;
// 1. Modify the state of the object (PromiseState)
self.PromiseState = 'fulfilled';
// 2. Set the result value of the object (PromiseResult)
self.PromiseResult = data;
// After the asynchronous task ends, execute all successful callback functions one by one
self.callbacks.forEach(element => {
element.onResolved(data)
});
};
function reject(data) {
// If the object state is not pending, Then go straight back , Do not execute the following code
if (self.PromiseState !== 'pending') return;
// 1. Modify the state of the object (PromiseState)
self.PromiseState = 'rejected';
// 2. Set the result value of the object (PromiseResult)
self.PromiseResult = data;
// After the asynchronous task ends, execute the failed callback functions one by one
self.callbacks.forEach(element => {
element.onRejected(data)
})
}
// The executor function is called synchronously internally , Directly take it and add a bracket behind it to synchronously call
try {
executor(resolve, reject);
} catch (e) {
reject(e);
}
}
// add to then Method
Promise.prototype.then = function (onResolved, onRejected) {
const self = this;
// Determine whether to pass in the parameters of the callback function
if(typeof onRejected !== 'function'){
onRejected = reason => {
throw reason;
}
}
if(typeof onResolved !== 'function'){
onResolved = value => value;
}
return new Promise((resolve, reject) => {
function callBack(type) {
try {
let res = type(self.PromiseResult);
if (res instanceof Promise) {
res.then(v => {
resolve(v);
}, r => {
reject(r);
})
} else {
resolve(res)
}
} catch (e) {
reject(e)
}
}
if (this.PromiseState === 'fulfilled') {
callBack(onResolved);
}
if (this.PromiseState === 'rejected') {
callBack(onRejected);
}
if (this.PromiseState === 'pending') {
this.callbacks.push({
onResolved: function () {
callBack(onResolved);
},
onRejected: function () {
callBack(onRejected);
}
})
}
});
}
// add to catch Method
Promise.prototype.catch = function(onRejected){
return this.then(undefined, onRejected);
}
3.14 Promise Encapsulation of methods in (resolve, reject, race, all)
3.14.1 Promise.resolve Method encapsulation
// add to Promise.resolve Method
Promise.resolve = function(value){
// return Promise object
return new Promise((resolve, reject)=>{
if(value instanceof Promise){
value.then(v=>{
resolve(value);
},r=>{
reject(value);
})
}else{
resolve(value);
}
});
}
3.14.2 Promise.reject Method encapsulation
// add to Promise.reject Method
Promise.reject = function(reason){
// Back to a new Promise object
return new Promise((resolve, reject)=>{
reject(reason);
});
}
3.14.3 Promise.all Method encapsulation
// add to Promise.all Method
Promise.all = function (promises) {
// Back to a new Promise object
return new Promise((resolve, reject) => {
// Record successful Promise Number
let count = 0;
// Save every successful result
let arr = [];
for (let i = 0; i < promises.length; i++) {
promises[i].then(v => {
count++;
arr[i] = v;
if (count === promises.length) {
resolve(arr);
}
}, r => {
reject(r)
});
}
});
}
3.14.4 Promise.race Method encapsulation
// add to Promise.race Method
Promise.race = function (promises) {
// Back to a new Promise object
return new Promise((resolve, reject) => {
for (let i = 0; i < promises.length; i++) {
// Who runs fast , Who changes the state
promises[i].then(v => {
resolve(v);
}, r => {
reject(r);
});
// After changing the State , There's no need to implement those coming in later , direct break
break;
}
});
}
3.14.5 then Asynchronous execution of a method


3.15 Promise Complete implementation
// Declaration constructor
function Promise(executor) {
// Add attribute
this.PromiseState = 'pending';
this.PromiseResult = null;
// Save the this value
const self = this;
// preservation then The callback function in
this.callbacks = [];
// because resolve and reject When used, it is a function , So define two functions
function resolve(data) {
// If the object state is not pending, Then go straight back , Do not execute the following code
if (self.PromiseState !== 'pending') return;
// 1. Modify the state of the object (PromiseState)
self.PromiseState = 'fulfilled';
// 2. Set the result value of the object (PromiseResult)
self.PromiseResult = data;
// After the asynchronous task ends, execute all successful callback functions one by one
setTimeout(() => {
self.callbacks.forEach(element => {
element.onResolved(data)
});
});
};
function reject(data) {
// If the object state is not pending, Then go straight back , Do not execute the following code
if (self.PromiseState !== 'pending') return;
// 1. Modify the state of the object (PromiseState)
self.PromiseState = 'rejected';
// 2. Set the result value of the object (PromiseResult)
self.PromiseResult = data;
// After the asynchronous task ends, execute the failed callback functions one by one
setTimeout(() => {
self.callbacks.forEach(element => {
element.onRejected(data)
});
});
}
// The executor function is called synchronously internally , Directly take it and add a bracket behind it to synchronously call
try {
executor(resolve, reject);
} catch (e) {
reject(e);
}
}
// add to then Method
Promise.prototype.then = function (onResolved, onRejected) {
const self = this;
// Determine whether to pass in the parameters of the callback function
if (typeof onRejected !== 'function') {
onRejected = reason => {
throw reason;
}
}
if (typeof onResolved !== 'function') {
onResolved = value => value;
}
return new Promise((resolve, reject) => {
function callBack(type) {
try {
let res = type(self.PromiseResult);
if (res instanceof Promise) {
res.then(v => {
resolve(v);
}, r => {
reject(r);
})
} else {
resolve(res)
}
} catch (e) {
reject(e)
}
}
if (this.PromiseState === 'fulfilled') {
setTimeout(() => {
callBack(onResolved);
})
}
if (this.PromiseState === 'rejected') {
setTimeout(() => {
callBack(onRejected);
})
}
if (this.PromiseState === 'pending') {
this.callbacks.push({
onResolved: function () {
callBack(onResolved);
},
onRejected: function () {
callBack(onRejected);
}
})
}
});
}
// add to catch Method
Promise.prototype.catch = function (onRejected) {
return this.then(undefined, onRejected);
}
// add to Promise.resolve Method
Promise.resolve = function (value) {
// return Promise object
return new Promise((resolve, reject) => {
if (value instanceof Promise) {
value.then(v => {
resolve(value);
}, r => {
reject(value);
})
} else {
resolve(value);
}
});
}
// add to Promise.reject Method
Promise.reject = function (reason) {
// Back to a new Promise object
return new Promise((resolve, reject) => {
reject(reason);
});
}
// add to Promise.all Method
Promise.all = function (promises) {
// Back to a new Promise object
return new Promise((resolve, reject) => {
// Record successful Promise Number
let count = 0;
// Save every successful result
let arr = [];
for (let i = 0; i < promises.length; i++) {
promises[i].then(v => {
count++;
arr[i] = v;
if (count === promises.length) {
resolve(arr);
}
}, r => {
reject(r)
});
}
});
}
// add to Promise.race Method
Promise.race = function (promises) {
// Back to a new Promise object
return new Promise((resolve, reject) => {
for (let i = 0; i < promises.length; i++) {
// Who runs fast , Who changes the state
promises[i].then(v => {
resolve(v);
}, r => {
reject(r);
});
// After changing the State , There's no need to implement those coming in later , direct break
break;
}
});
}
3.16 class Version implementation
class Promise {
// Construction method
constructor(executor) {
// Add attribute
this.PromiseState = 'pending';
this.PromiseResult = null;
// Save the this value
const self = this;
// preservation then The callback function in
this.callbacks = [];
// because resolve and reject When used, it is a function , So define two functions
function resolve(data) {
// If the object state is not pending, Then go straight back , Do not execute the following code
if (self.PromiseState !== 'pending') return;
// 1. Modify the state of the object (PromiseState)
self.PromiseState = 'fulfilled';
// 2. Set the result value of the object (PromiseResult)
self.PromiseResult = data;
// After the asynchronous task ends, execute all successful callback functions one by one
setTimeout(() => {
self.callbacks.forEach(element => {
element.onResolved(data)
});
});
};
function reject(data) {
// If the object state is not pending, Then go straight back , Do not execute the following code
if (self.PromiseState !== 'pending') return;
// 1. Modify the state of the object (PromiseState)
self.PromiseState = 'rejected';
// 2. Set the result value of the object (PromiseResult)
self.PromiseResult = data;
// After the asynchronous task ends, execute the failed callback functions one by one
setTimeout(() => {
self.callbacks.forEach(element => {
element.onRejected(data)
});
});
}
// The executor function is called synchronously internally , Directly take it and add a bracket behind it to synchronously call
try {
executor(resolve, reject);
} catch (e) {
reject(e);
}
}
// then Method encapsulation
then(onResolved, onRejected) {
const self = this;
// Determine whether to pass in the parameters of the callback function
if (typeof onRejected !== 'function') {
onRejected = reason => {
throw reason;
}
}
if (typeof onResolved !== 'function') {
onResolved = value => value;
}
return new Promise((resolve, reject) => {
function callBack(type) {
try {
let res = type(self.PromiseResult);
if (res instanceof Promise) {
res.then(v => {
resolve(v);
}, r => {
reject(r);
})
} else {
resolve(res)
}
} catch (e) {
reject(e)
}
}
if (this.PromiseState === 'fulfilled') {
setTimeout(() => {
callBack(onResolved);
})
}
if (this.PromiseState === 'rejected') {
setTimeout(() => {
callBack(onRejected);
})
}
if (this.PromiseState === 'pending') {
this.callbacks.push({
onResolved: function () {
callBack(onResolved);
},
onRejected: function () {
callBack(onRejected);
}
})
}
});
}
// catch Method encapsulation
catch(onRejected) {
return this.then(undefined, onRejected);
}
// static Indicates that this method belongs to class , Instead of belonging to the instance object
// add to Promise.resolve Method
static resolve = function (value) {
// return Promise object
return new Promise((resolve, reject) => {
if (value instanceof Promise) {
value.then(v => {
resolve(value);
}, r => {
reject(value);
})
} else {
resolve(value);
}
});
}
// add to Promise.reject Method
static reject = function (reason) {
// Back to a new Promise object
return new Promise((resolve, reject) => {
reject(reason);
});
}
// add to Promise.all Method
static all = function (promises) {
// Back to a new Promise object
return new Promise((resolve, reject) => {
// Record successful Promise Number
let count = 0;
// Save every successful result
let arr = [];
for (let i = 0; i < promises.length; i++) {
promises[i].then(v => {
count++;
arr[i] = v;
if (count === promises.length) {
resolve(arr);
}
}, r => {
reject(r)
});
}
});
}
// add to Promise.race Method
static race = function (promises) {
// Back to a new Promise object
return new Promise((resolve, reject) => {
for (let i = 0; i < promises.length; i++) {
// Who runs fast , Who changes the state
promises[i].then(v => {
resolve(v);
}, r => {
reject(r);
});
// After changing the State , There's no need to implement those coming in later , direct break
break;
}
});
}
}
边栏推荐
- What are the important applications of MES system in manufacturing enterprises
- go 学习01
- Software testing interview question: why should we carry out testing in a team?
- 软件测试面试题:你所熟悉的软件测试类型有哪些?
- Codeforces Round #810 (Div. 2)A~C题解
- 【Star项目】小帽飞机大战(五)
- Software testing interview question: what do you think is the key to good test case design?
- 考研数学一元微分学证明题常见题型方法
- 测试/开发程序员的级别“陷阱“,级别不是衡量单维度的能力......
- Unittest unit test framework full stack knowledge
猜你喜欢

Starfish OS X metabell strategic cooperation, metauniverse business ecosystem further

11-Django-基础篇-数据库操作

Solution of digital commerce cloud supply chain centralized purchase management system: centralized purchase system management mode, digital control of enterprise materials

一种比读写锁更快的锁,还不赶紧认识一下

Talk to ye Yanxiu, an atlassian certification expert: where should Chinese users go when atlassian products enter the post server era?

FreeRTOS kernel summary

Structure pseudo class selector - find single - find multiple - nth of type and pseudo elements

Five basic data structures of redis

JS what situations can't use json Parse, json.stringify deep copy and a better deep copy method

BGP federal experiment
随机推荐
QGIS mapping: vector data mapping process and export
Common problem types and methods of mathematical univariate differential proof problems in postgraduate entrance examination
Sample imbalance - entry 0
微信小程序图片根据屏幕比例缩放
华为APP UI自动化测试岗面试真题,真实面试经历。
Aike AI frontier promotion (7.14)
Record a production deadlock
Promise从入门到精通(第3章 自定义(手写)Promise)
MPLS tunnel experiment
Software testing interview question: why should we carry out testing in a team?
软件测试面试题:为什要在一个团队中开展测试工作?
样本不均衡-入门0
FreeRTOS kernel summary
Data output - image annotation and annotation
Fiddler mobile packet capturing agent settings (for Huawei glory 60s)
mysql创建存储过程---------[HY000][1418] This function has none of DETERMINISTIC, NO SQL
Unittest单元测试框架全栈知识
SFTP file / folder upload server
The principle and implementation of loss function cross entropy
mongodb/mongoTemplate.upsert批量插入更新数据的实现