最美情侣中文字幕电影,在线麻豆精品传媒,在线网站高清黄,久久黄色视频

歡迎光臨散文網(wǎng) 會員登陸 & 注冊

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

2022-05-07 23:48 作者:江火漁楓  | 我要投稿

```

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)}

);


```






手寫Promise核心代碼 - JavaScript前端Web工程師的評論 (共 條)

分享到微博請遵守國家法律
米脂县| 仁怀市| 青田县| 新乡县| 崇仁县| 修武县| 高陵县| 金昌市| 招远市| 莱阳市| 托克逊县| 大连市| 东港市| 五峰| 元朗区| 曲阳县| 奉贤区| 咸阳市| 北川| 宁安市| 南召县| 唐河县| 资阳市| 长子县| 盐边县| 墨玉县| 黄浦区| 佛学| 犍为县| 阿拉善右旗| 左权县| 平塘县| 淮滨县| 延安市| 大渡口区| 长寿区| 东丰县| 沧州市| 固镇县| 锡林浩特市| 灯塔市|