javascript yield
代码:
function delay(time) { return new Promise(function (resolve, reject) { setTimeout(() => { resolve(); }, time); }); } function* output() { yield delay(500).then(() => console.log(1)); yield (function () { console.log(2); return 'aa' })() yield delay(200).then(() => console.log(3)); yield (function () { console.log(4); return 'aa' })() } function runGen(gen, next) { const item = gen.next(); if (item.done) return; const { value } = item if (value instanceof Promise) { value.then(() => runGen(gen)) } else { runGen(gen) } } runGen(output());
输出: