async
函数的实现原理,就是将 Generator
函数和自动执行器,包装在一个函数里。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| function _async (genF) { return new Promise(function (resolve, reject) { const gen = genF(); function step (nextF) { let next; try { next = nextF(); } catch (e) { return reject(e); } if (next.done) { return resolve(next.value); } Promise.resolve(next.value).then( function (v) { step({ function () { return gen.next(v); } }); }, function (e) { step({ function () { return gen.throw(e); } }); } ); } step(function () { return gen.next(undefined); }); }); }
|