We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? # to your account
/** * slice() reference. */ var slice = Array.prototype.slice; /** * Expose `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 */ // 有参数的 generator 调用 // var fn = co.wrap(function* (val) { // return yield Promise.resolve(val); // }); // fn(true).then(function (val) { // console.log(val); // true // }); co.wrap = function (fn) { // 存了一个指针指向原 generator 函数 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) { // 缓存 this var ctx = this; // 获取 co 函数从第二个参数到最后一个参数,除 gen 之外的其他参数 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 // 返回的是 Promise(这是为什么可以用 then 和 catch 的根源) return new Promise(function(resolve, reject) { // 执行外部传入的 gen if (typeof gen === 'function') gen = gen.apply(ctx, args); // 如果不具备 next 属性或者不是一个函数 if (!gen || typeof gen.next !== 'function') return resolve(gen); onFulfilled(); /** * @param {Mixed} res * @return {Promise} * @api private */ // 为了能够捕捉抛出的错误 function onFulfilled(res) { var ret; try { ret = gen.next(res); // generator 函数指针移动到了一个位置 } catch (e) { return reject(e); } next(ret); // 反复调用 } /** * @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) { // 如果执行完成,直接调用 resolve 把 promise 置为成功状态 if (ret.done) return resolve(ret.value); // 将 ret 的 value 转换为 Promise 形式 var value = toPromise.call(ctx, ret.value); // 直接给新的 promise 添加 onFulfilled, onRejected if (value && isPromise(value)) return value.then(onFulfilled, onRejected); // 抛出错误,yield 后只能跟着指定的下列这几种类型 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. * * @param {Mixed} obj * @return {Promise} * @api private */ function toPromise(obj) { // obj 不存在,直接返回 if (!obj) return obj; // 如果 obj 已经是 Promise,直接返回 if (isPromise(obj)) return obj; // 如果是个 generator 函数或者 generator 生成器,执行 if (isGeneratorFunction(obj) || isGenerator(obj)) return co.call(this, obj); // 如果是个普通的函数(需要符合thunk函数规范),就将该函数包装成 Promise 的形式 if ('function' == typeof obj) return thunkToPromise.call(this, obj); // 如果 obj 是 array,直接用 Promise.all 包装 if (Array.isArray(obj)) return arrayToPromise.call(this, obj); // 如果 obj 是 object if (isObject(obj)) return objectToPromise.call(this, obj); return obj; } /** * Convert a thunk to a promise. * * @param {Function} * @return {Promise} * @api private */ // thunk 函数具备以下两个要素: // 有且只有一个参数是 callback 的函数 // callback 的第一个参数是 error function thunkToPromise(fn) { var ctx = this; // 将 thunk 函数包装成 Promise return new Promise(function (resolve, reject) { fn.call(ctx, function (err, res) { if (err) return reject(err); if (arguments.length > 2) res = slice.call(arguments, 1); 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(); // 获取 obj 的keys var keys = Object.keys(obj); // 存储 obj 中是 Promise 的属性 var promises = []; for (var i = 0; i < keys.length; i++) { var key = keys[i]; // 转换为 Promise 形式 var promise = toPromise.call(this, obj[key]); // 如果是结果是 Promise,则用 defer 函数对 results 的某个 Promise 返回值进行修改 if (promise && isPromise(promise)) defer(promise, key); // 如果不是就直接返回 else results[key] = obj[key]; } // 等待所有 promise 执行完毕,返回结果 return Promise.all(promises).then(function () { return results; }); function defer(promise, key) { // predefine the key in the result // 预定义 results[key] = undefined; promises.push(promise.then(function (res) { // 运行成功结果赋值给 results results[key] = res; })); } } /** * Check if `obj` is a promise. * * @param {Object} obj * @return {Boolean} * @api private */ function isPromise(obj) { return 'function' == typeof obj.then; } /** * Check if `obj` is a generator. * * @param {Mixed} obj * @return {Boolean} * @api private */ function isGenerator(obj) { return 'function' == typeof obj.next && 'function' == typeof obj.throw; } /** * Check if `obj` is a generator function. * * @param {Mixed} obj * @return {Boolean} * @api private */ function isGeneratorFunction(obj) { var constructor = obj.constructor; if (!constructor) return false; if ('GeneratorFunction' === constructor.name || 'GeneratorFunction' === constructor.displayName) return true; return isGenerator(constructor.prototype); } /** * Check for plain object. * * @param {Mixed} val * @return {Boolean} * @api private */ function isObject(val) { return Object == val.constructor; }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
yield 后面常见的可以跟的类型
分析源码
The text was updated successfully, but these errors were encountered: