The principle of
asyncEssentially, a serial promise is converted to a parallel (synchronous) promise, and the same effect can be achieved by converting it to serial using an autoexecutorawaitReplace withyield, convert to generate, and then create its iterator, passing next to move the function to the next stepyieldDefine the autoexecutor: Determine the done attribute returned by Next, astrue, the end recursion is nottrueThe recursive executor uses promise.then(... Next (res)) or next(value), and finally parallel to serialCopy the code
implementation
async function asyncDetail(){
// do something...
console.log('aaa');
await a();
// do something...
console.log('bbb');
await b();
// do something...
console.log('ccc');
awaitc(); } Step 1:function* asyncDetailGenerate(){
// do something...
console.log('aaa');
const a = yield test();
console.log('a');
// do something...
console.log('bbb');
const b = yield test();
console.log('b');
const d = yield 'dddd';
console.log(d);
// do something...
console.log('ccc');
const c = yield test();
console.log('c'); } Step 2:construnner = asyncDetailGenerate(); Step 3: Customize the actuatorconst autoRunner = (runner,{value,done}) = >{
if(done){
return value;
}else{
if(value instanceof Promise){
value.then(res= >{
constnextResult = runner.next(res); autoRunner(runner,nextResult); })}else{
constnextResult = runner.next(value); autoRunner(runner,nextResult); }} autoRunner(runner,runner. Next ());Copy the code