Created
January 18, 2018 03:17
-
-
Save xinlc/0e6722476d00d5fa67cc10cdfd958723 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function co(gen) { | |
var ctx = this; | |
return new Promise(function(resolve, reject) { | |
if (typeof gen === 'function') gen = gen.call(ctx); | |
if (!gen || typeof gen.next !== 'function') return resolve(gen); | |
onFulfilled(); | |
function onFulfilled(res) { | |
var ret; | |
try { | |
ret = gen.next(res); | |
} catch (e) { | |
return reject(e); | |
} | |
next(ret); | |
} | |
}); | |
} | |
function next(ret) { | |
if (ret.done) return resolve(ret.value); | |
var value = toPromise.call(ctx, ret.value); | |
if (value && isPromise(value)) return value.then(onFulfilled, onRejected); | |
return onRejected( | |
new TypeError( | |
'You may only yield a function, promise, generator, array, or object, ' | |
+ 'but the following object was passed: "' | |
+ String(ret.value) | |
+ '"' | |
) | |
); | |
} | |
/* | |
// 数组的写法 | |
co(function* () { | |
var res = yield [ | |
Promise.resolve(1), | |
Promise.resolve(2) | |
]; | |
console.log(res); | |
}).catch(onerror); | |
// 对象的写法 | |
co(function* () { | |
var res = yield { | |
1: Promise.resolve(1), | |
2: Promise.resolve(2), | |
}; | |
console.log(res); | |
}).catch(onerror); | |
co(function* () { | |
var values = [n1, n2, n3]; | |
yield values.map(somethingAsync); | |
}); | |
function* somethingAsync(x) { | |
// do something async | |
return y | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment