co源码分析(promise版本4.6.0)
co的promise版本,就是将函数,generator,generator function,对象,数组等全部转换为promise,在promise的then中,递归的去执行下一个异步流程。其中,object中的promise,通过循环并行执行,array中的异步流程,通过Promise.all来并行执行。
源码如下:
//方便截取参数 var slice = Array.prototype.slice; //导出co module.exports = co['default'] = co.co = co; /** * Wrap the given generator `fn` into a * function that returns a promise. * This is a separate function so that * every `co()` call doesn't create a new, * unnecessary closure. * * @param {GeneratorFunction} fn * @return {Function} * @api public */ // 返回一个创建promise的函数,是为了方便重复调用同一个异步流程??? co.wrap = function (fn) { createPromise.__generatorFunction__ = fn; return createPromise; function createPromise() { return co.call(this, fn.apply(this, arguments)); } }; /** * Execute the generator function or a generator * and return a promise. * * @param {Function} fn * @return {Promise} * @api public */ function co(gen) { var ctx = this; var args = slice.call(arguments, 1); // we wrap everything in a promise to avoid promise chaining, // which leads to memory leak errors. // see https://github.com/tj/co/issues/180 return new Promise(function(resolve, reject) { //gen是generator function,执行gen,得到generator if (typeof gen === 'function') gen = gen.apply(ctx, args); //gen不是generator,返回 if (!gen || typeof gen.next !== 'function') return resolve(gen); //执行正确状态函数,开始递归流程 onFulfilled(); /** * @param {Mixed} res * @return {Promise} * @api private */ function onFulfilled(res) { var ret; try { //切换一次主generator状态,得到一次执行结果 ret = gen.next(res); } catch (e) { return reject(e); } //向后递归执行 next(ret); return null; } /** * @param {Error} err * @return {Promise} * @api private */ function onRejected(err) { var ret; try { //报错,则抛出 ret = gen.throw(err); } catch (e) { return reject(e); } //继续向后执行 next(ret); } /** * Get the next value in the generator, * return a promise. * * @param {Object} ret * @return {Promise} * @api private */ function next(ret) { //执行完毕,返回 if (ret.done) return resolve(ret.value); //将ret.value转换为promise var value = toPromise.call(ctx, ret.value); //在promise的then中继续执行后面的异步函数 if (value && isPromise(value)) return value.then(onFulfilled, onRejected); //无法转换为promise,则抛出类型错误 return onRejected(new TypeError('You may only yield a function, promise, generator, array, or object, ' + 'but the following object was passed: "' + String(ret.value) + '"')); } }); } // Convert a `yield`ed value into a promise. // 所有类型统统转换为promise function toPromise(obj) { if (!obj) return obj; if (isPromise(obj)) return obj; //是generator function或generator,则用co调用,返回一个promise if (isGeneratorFunction(obj) || isGenerator(obj)) return co.call(this, obj); //函数转promise if ('function' == typeof obj) return thunkToPromise.call(this, obj); //数组转promise if (Array.isArray(obj)) return arrayToPromise.call(this, obj); //对象转promise if (isObject(obj)) return objectToPromise.call(this, obj); return obj; } //thunk函数转promise function thunkToPromise(fn) { var ctx = this; return new Promise(function (resolve, reject) { fn.call(ctx, function (err, res) { //有错误,接reject if (err) return reject(err); if (arguments.length > 2) res = slice.call(arguments, 1); //无错误,用执行结果res来resolve resolve(res); }); }); } /** * Convert an array of "yieldables" to a promise. * Uses `Promise.all()` internally. * * @param {Array} obj * @return {Promise} * @api private */ function arrayToPromise(obj) { return Promise.all(obj.map(toPromise, this)); } /** * Convert an object of "yieldables" to a promise. * Uses `Promise.all()` internally. * * @param {Object} obj * @return {Promise} * @api private */ function objectToPromise(obj){ //构造一个同类型对象 var results = new obj.constructor(); var keys = Object.keys(obj); var promises = []; for (var i = 0; i < keys.length; i++) { var key = keys[i]; //对象里面的所有value转换为promise var promise = toPromise.call(this, obj[key]); //是promise,就通过defer方法将promise执行结果放到results中 if (promise && isPromise(promise)) defer(promise, key); //不是promise,就仅记录value else results[key] = obj[key]; } return Promise.all(promises).then(function () { return results; }); function defer(promise, key) { // predefine the key in the result // ??? 为什么要先占坑 results[key] = undefined; // 执行promise,将结果记录到results中 promises.push(promise.then(function (res) { results[key] = res; })); } } //判断是promise function isPromise(obj) { return 'function' == typeof obj.then; } //判断是generator function isGenerator(obj) { return 'function' == typeof obj.next && 'function' == typeof obj.throw; } //判断是generator function,其返回值是generator //形如 function* {...} function isGeneratorFunction(obj) { var constructor = obj.constructor; if (!constructor) return false; if ('GeneratorFunction' === constructor.name || 'GeneratorFunction' === constructor.displayName) return true; return isGenerator(constructor.prototype); } //判断是对象 function isObject(val) { return Object == val.constructor; }