手寫Promise核心代碼 - JavaScript前端Web工程師

```
const { reject } = require("core-js/fn/promise");
class Commitment {
??static PENDING = '待定';
??static FULFILLED = '成功';
??static REJECTED = '拒絕';
??constructor(func){
????this.status = Commitment.PENDING;
????this.result = null;
????this.resolveCallbacks = [];
????this.rejectCallbacks = [];
????//***bind(this) 將this指向新創(chuàng)建的對象 commitment ****/
????//func(this.resolve.bind(this), this.reject.bind(this));
????//原生promise調(diào)用than 可以把錯誤的信息做為內(nèi)容輸出出來 調(diào)用方式如下
????/***
?????* let promise = new Promise((resolve, reject) => {
?????*?throw new Error('輸出錯誤信息');
?????* })
?????* ** */
????try{
??????func(this.resolve.bind(this), this.reject.bind(this));
????} catch (error){
??????//這里是直接執(zhí)行不是創(chuàng)建實例后再執(zhí)行 不用綁定this
??????this.reject(error);
????}
??}
??resolve(){
????setTimeout(() => {
??????if(this.status === Commitment.PENDING){
????????this.status = Commitment.FULFILLED;
????????this.result = result;
????????this.resolveCallbacks.forEach(callback =>{
??????????callback(result)
????????})
??????}
????});
??}
??reject(){
????setTimeout(() => {
??????if(this.status === Commitment.PENDING){
????????this.status = Commitment.REJECTED;
????????this.result = result;
????????this.rejectCallbacks.forEach(callback => {
??????????callback(result)
????????})
??????}
????});
??}
??than(onFULFILLED, onREJECTED){
????//為實現(xiàn) .than鏈?zhǔn)秸{(diào)用?方法內(nèi)返回new Commitment
????return new Commitment((resolve, reject) => {
??????// than 里面的兩個參數(shù)不是函數(shù)則不被執(zhí)行
??????//解決思路 賦值空函數(shù)
??????onFULFILLED = typeof onFULFILLED === 'function' ? onFULFILLED : () => {};
??????onREJECTED = typeof onREJECTED === 'function' ? onREJECTED : () => {};
??????if(this.status === Commitment.PENDING){
????????this.resolveCallbacks.push(onFULFILLED);
????????this.rejectCallbacks.push(onREJECTED);
??????}
??????if(this.status === Commitment.FULFILLED){
????????onFULFILLED(this.result);
??????}
??????if(this.status === Commitment.REJECTED){
????????onREJECTED(this.result);
??????}
????})
??}
}
let commitment = new Commitment((resolve, reject) => {
??resolve('這次一定');
});
commitment.than(
??result => {console.log(result)},
??result => {console.log(result.message)}
).than(
??result => {console.log(result)},
??result => {console.log(result.message)}
);
```
