Promise

整體框架

const PENDING = 'pending'; // 初始態(tài)
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
function Promise(executor) {
    let _this = this; // 當前Promise實例
    _this.status = PENDING;
    // 定義存放成功的回調(diào)函數(shù)數(shù)組
    _this.onResolvedCallbacks = [];
    // 定義存放失敗的回調(diào)函數(shù)數(shù)組
    _this.onRejectedCallbacks = [];

    // 此函數(shù)執(zhí)行可能出異常
    // 調(diào)用此方法 如果是pending,就可以轉(zhuǎn)為resolve,若是resolve或者reject不處理
    function resolve(value) {}
    function reject(error) {}
    try{
        executor(resolve, reject);
    }catch(e) {
        // 函數(shù)執(zhí)行失敗了
        reject(e);
    }
}

對照官方文檔



實現(xiàn)部分狀態(tài)改變的部分

function resolve(value) {
    if(_this.status === PENDING){
        _this.status = FULFILLED;
        _this.value = value;
        // 調(diào)用成功的回調(diào)
       _this.onResolvedCallbacks.forEach(cb => cb(_this.value));
    }
}
function reject(error) {
    if(_this.status === PENDING){
        _this.status = REJECTED;
        _this.value = error; // 失敗的原因
        _this.onRejectedCallbacks.forEach(cb => cb(_this.value))
     }
}
// onFulfilled 是用來接收promise成功的值或者失敗的原因
// 值的穿透
Promise.prototype.then = function (onFulfilled, onRejected) {
    // 如果成功和失敗的回調(diào)沒有傳,表示這個then沒有任何邏輯,只會把值往后拋
    onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
    onRejected = typeof onRejected === 'function' ? onRejected : reason => {throw reason};
};

then方法 不管成功還是失敗狀態(tài),都要返回一個promise對象,如果是pending狀態(tài)的話,依然需要等待狀態(tài)改變



// onFulfilled 是用來接收promise成功的值或者失敗的原因
// 值的穿透
Promise.prototype.then = function (onFulfilled, onRejected) {
    // 如果成功和失敗的回調(diào)沒有傳,表示這個then沒有任何邏輯,只會把值往后拋
    onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
    onRejected = typeof onRejected === 'function' ? onRejected : reason => {throw reason};
    // 當前promise狀態(tài)已經(jīng)是成功態(tài), onFulfilled直接取傳遞過來的值
    let _this = this;
    let promise2;
    if(this.status === FULFILLED){
        return promise2 = new Promise(function (resolve, reject) {
            try{
                let x = onFulfilled(_this.value);
                // 如果獲取到了返回值x,會走解析promise的過程
                resovlePromise(promise2, x, resolve, reject);
            } catch(e) {
                reject(e);
            }
        });
    }
    if(this.status === REJECTED){
        try{
            let x = onRejected(_this.value);
            resovlePromise(promise2, x, resolve, reject);
        } catch(e) {
            reject(e);
        }

    }
    // 如果是pending狀態(tài)
    if(this.status === PENDING){

        _this.onResolvedCallbacks.push(function () {
            try{
                let x = onFulfilled(_this.value);
                resovlePromise(promise2, x, resolve, reject);
            } catch(e) {
                reject(e);
            }
        });
        _this.onRejectedCallbacks.push(function () {
            try{
                let x = onRejected(_this.value);
                resovlePromise(promise2, x, resolve, reject);
            } catch(e) {
                reject(e);
            }

        });
    }
    return new Promise(x);
};

處理then里面的resolve


function resovlePromise(promise2, x, resolve, reject) {
    if(promise2 === x){
        throw TypeError("循環(huán)調(diào)用");
    }
    let called = false; // promise2是否resolved或者reject(狀態(tài)只能改一次)
    if(x instanceof Promise){
        // x是pending狀態(tài)的話,promise2就得等待他處理完成
        if(x.status === PENDING){
           x.then(function (y) {
               resovlePromise(promise2, y, resolve, reject);
           }, reject);
           // 不是pending就把x傳遞過來的值給promise2
        } else {
            x.then(resolve, reject);
        }
        // x是對象或者函數(shù) 只要有then方法就可
    } else if(x !== null && (typeof x === 'object' || typeof x === 'function')){
        try{
            let then = x.then;
            if(typeof then === 'function'){
                // 當我們的promise和別人的promise進行交互,編寫這段代碼要考慮到亂寫的內(nèi)容
                then.call(x, function (y) {
                    // 如果promise2已經(jīng)成功或失敗,就不會再處理
                    if(called){
                        return;
                    }
                    called = true;
                    // 遞歸調(diào)用
                    resovlePromise(promise2, y, resolve, reject);
                }, function (err) {
                    if(called){
                        return;
                    }
                    called = true;
                    reject(err);
                });
            } else {
                // 這一步說明x不是一個thenable對象 直接把他當成值resolve promise2
                resolve(x);
            }
        }catch (e) {
            if(called){
                return;
            }
            called = true;
            reject(e);
        }
    } else {
        // 普通值的話就用x去resolve promise2
        resolve(x);
    }
}

Promise.all/Promise.race

function gen(times, cb) {
    let result = [], count = 0;
    return function (i, data) {
        result[i] = data;
        if(++count === times){
            cb(result);
        }
    }
}

// Promise.all 接收一個promise數(shù)組, 如果全部完成了promise才會成功
// 只要有一個失敗,那么promise就失敗
Promise.call = function (promises) {
  return new Promise(function (resolve, reject) {
      let done = gen(promises.length, resolve);
      for (let i = 0; i < promises.length; i++) {
          promises[i].then(function (data) {
              done(i, data);
          }, reject);
      }
  });
};

// Promise.race 接收一個promise數(shù)組, 誰先完成就是誰的狀態(tài)
// 不管成功還是失敗
Promise.race = function (promises) {
    return new Promise(function (resolve, reject) {
        for (let i = 0; i < promises.length; i++) {
            promises[i].then(resolve, reject);
        }
    });
};
Promise.resolve = function (value) {
  return new Promise(function(resolve){
      resolve(value);
  })  
};

Promise.reject = function (reason) {
    return new Promise(function(resolve, reject){
        reject(reason);
    })
};

Q一個Promise庫,angular.js里面就是用的它,Q的實現(xiàn)原理及用法

// let Q = require('q');
let Q = {
    defer() {
        let success, error;
        return {
            resolve(data){
                success(data);
            },
            reject(error){
                error(error);
            },
            promise: {
                then(onfulfilled, onRejected){
                    success = onfulfilled;
                    error = onRejected;
                }
            }
        }
    }
};


let fs = require('fs');
function readFlie(filename) {
    let defer = Q.defer();
    fs.readFile(filename, 'utf8', function (err, data) {
        if(err){
            defer.reject(err);
        } else {
            defer.resolve(data)
        }
    });
    return defer.promise;
}
readFlie('data.txt').then(function (data) {
    console.log(data);
});
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Promise 對象 Promise 的含義 Promise 是異步編程的一種解決方案,比傳統(tǒng)的解決方案——回調(diào)函...
    neromous閱讀 8,834評論 1 56
  • 目錄:Promise 的含義基本用法Promise.prototype.then()Promise.prototy...
    BluesCurry閱讀 1,565評論 0 8
  • 一、Promise的含義 Promise在JavaScript語言中早有實現(xiàn),ES6將其寫進了語言標準,統(tǒng)一了用法...
    Alex灌湯貓閱讀 888評論 0 2
  • //本文內(nèi)容起初摘抄于 阮一峰 作者的譯文,用于記錄和學(xué)習(xí),建議觀者移步于原文 概念: 所謂的Promise,...
    曾經(jīng)過往閱讀 1,320評論 0 7
  • MAFFT:multiple alignment program for amino acid or nucleo...
    Xylona_MS閱讀 4,440評論 0 0

友情鏈接更多精彩內(nèi)容