promisify 的過程

chaos同學發表於2018-09-25

bluebird 中的promisify的原型原始碼是

Promise.promisify = function (fn, options) {
    if (typeof fn !== "function") {
        throw new TypeError("expecting a function but got " + util.classString(fn));
    }
    if (isPromisified(fn)) {
        return fn;
    }
    options = Object(options);
    var receiver = options.context === undefined ? THIS : options.context;
    var multiArgs = !!options.multiArgs;
    var ret = promisify(fn, receiver, multiArgs);
    util.copyDescriptors(fn, ret, propsFilter);
    return ret;
};
複製程式碼

可以看到在判斷了是否是函式的同時判斷了fn是否已經被promise化過。 這裡的引數以(fn,undefined)為例,呼叫的promisify函式傳入的引數是(fn,{},false)

function promisify(callback, receiver, multiArgs) {
    return makeNodePromisified(callback, receiver, undefined,
                                callback, null, multiArgs);
}
複製程式碼

promisify實際是包裝了makeNodePromisified這個函式,對引數進行了傳遞

    var makeNodePromisified = canEvaluate
        ? makeNodePromisifiedEval
        : makeNodePromisifiedClosure;
複製程式碼

makeNodePromisified這個函式通過canEvaluate這個變數進行了呼叫函式的判斷,這是一個判斷執行環境是否是瀏覽器的變數。這裡我們呼叫的是makeNodePromisifiedClosure這個函式

function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) {
    var defaultThis = (function() {return this;})();
    var method = callback;
    if (typeof method === "string") {
        callback = fn;
    }
    function promisified() {
        var _receiver = receiver;
        if (receiver === THIS) _receiver = this;
        var promise = new Promise(INTERNAL);
        promise._captureStackTrace();
        var cb = typeof method === "string" && this !== defaultThis
            ? this[method] : callback;
        var fn = nodebackForPromise(promise, multiArgs);//變成promise
        try {
            cb.apply(_receiver, withAppended(arguments, fn));//呼叫傳入的cb
        } catch(e) {
            promise._rejectCallback(maybeWrapAsError(e), true, true);
        }
        if (!promise._isFateSealed()) promise._setAsyncGuaranteed();
        return promise;
    }
    util.notEnumerableProp(promisified, "__isPromisified__", true);
    return promisified;
}
複製程式碼

這裡先把_receiver繫結在this上,呼叫nodebackForPromise返回一個promise賦給fn, nodebackForPromise的原始碼是

function nodebackForPromise(promise, multiArgs) {
    return function(err, value) {
        if (promise === null) return;
        if (err) {
            var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
            promise._attachExtraTrace(wrapped);
            promise._reject(wrapped);
        } else if (!multiArgs) {
            promise._fulfill(value);
        } else {
            var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];};
            promise._fulfill(args);
        }
        promise = null;
    };
}
複製程式碼

可以看到這裡沒有錯誤就呼叫promise._fulfill(value),如果丟擲了錯誤就呼叫promise._reject處理,上面cb.apply(_receiver, withAppended(arguments, fn))實際上可以看做cb.apply(this,arguments,fn)這裡的fn即為nodebackForPromise返回的promise,funtion(err,value)這種形式也非常有node非同步函式的特徵。因此函式的的執行是在呼叫非同步函式cb完成後呼叫回撥函式fn這樣就進入了promise中。即將非同步函式promise化了。

相關文章