当前位置:网站首页>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;
}
});
}
}
边栏推荐
- 软件测试面试题:测试计划工作的目的是什么?测试计划工作的内容都包括什么?其中哪些是最重要的?
- Redis设计规范
- Enterprise operation and maintenance practice - using aliyun container image service to pull and build images of overseas GCR and quay warehouses
- Solution of digital commerce cloud supply chain centralized purchase management system: centralized purchase system management mode, digital control of enterprise materials
- 二叉树的遍历和性质
- [website construction] update SSL certificate with acme.sh: change zerossl to letsencrypt
- 53: Chapter 5: develop admin management service: 6: develop [admin administrator exit login, interface]; (one point: when we want to modify a value with a certain coding method, the new value should b
- 每条你收藏的资讯背后,都离不开TA
- 软件测试面试题:你认为做好测试用例设计工作的关键是什么?
- shell正则和元字符
猜你喜欢

BGP federal experiment

Starfish Os X MetaBell战略合作,元宇宙商业生态更进一步

Completely delete MySQL in Linux system

Starfish OS X metabell strategic cooperation, metauniverse business ecosystem further
![Likeshop takeout ordering system [100% open source, no encryption]](/img/e6/a73aa817b5b30339d755aa53708072.png)
Likeshop takeout ordering system [100% open source, no encryption]

Embedded classic communication protocol

Forget the root password
![[Taichi] draw a regular grid in Tai Chi](/img/48/14e825562afa3ffba96296799617f7.png)
[Taichi] draw a regular grid in Tai Chi

In it, there is a million talent gap, and the salary rises, but it is not capped

C# 使用Abp仓储访问数据库时报错记录集
随机推荐
数据输出-图片注释、标注
The principle and implementation of loss function cross entropy
Shell regular and metacharacters
新零售业态下,零售电商RPA助力重塑增长
Promise从入门到精通(第3章 自定义(手写)Promise)
云原生爱好者周刊:Prometheus 架构演进之路
Under the new retail format, retail e-commerce RPA helps reshape growth
The petrochemical industry is facing the tide of rising prices, and the digital dealer distribution system platform enables dealers and stores
What devices does devicexplorer OPC server support? This article has listed
Gbase 8C transaction ID and snapshot (V)
Promise从入门到精通 (第1章 Promise的介绍和基本使用)
Hcip 13th day notes
UE4 unreal ndisplay plug-in easy to use three fold screen details
视频常用分辨率
微信小程序图片根据屏幕比例缩放
【数据库数据恢复】SQL Server数据库磁盘空间不足的数据恢复案例
Starfish Os打造的元宇宙生态,跟MetaBell的合作只是开始
day7
QGIS mapping: vector data mapping process and export
都在说DevOps,你真正了解它吗?