我一直在学习Promise、await和async函数。在学习Promise阶段,我偶然发现了这个:
async function async1(){
console.log('Async 1');
await async2(); // *
console.log('AFter Async 1');
}
async function async2(){
console.log('FROM async 2');
}
async1();
console.log('Synchronous'); //**
Async 1
FROM async 2
Synchronous
AFter Async 1
代码是如何从*跳到**的?这里如何使用微任务?
async
function creates a promise to report the completion of that function's work. In the function, doing areturn x
(wherex
isn't a promise/thenable) fulfills theasync
function's promise (potentially queuing microtasks), and doing athrow
(or... - undefinedthrow
未被捕获)会拒绝该承诺(可能排队微任务)。(在p
是一个承诺的情况下使用return p
,将会解决async
函数的承诺为p
,这可能会履行它,拒绝它,或者保持悬而未决。解决!=履行!=解决,但人们经常混淆它们;详细信息请参阅我的博客。)使用await
,函数的代码在其之后,等待回调(在承诺工作/微任务中),当/如果等待的承诺被解决。希望这有所帮助! - undefinedasync
函数 -- 就像任何其他代码一样 -- 也可以直接通过在浏览器、Node.js 和 Deno 上使用queueMicrotask
来排队一个微任务。) - undefined