console.log('======== main task start ========'); new Promise(resolve => { console.log('create micro task 1'); resolve(); }).then(() => { console.log('micro task 1 callback'); setTimeout(() => { console.log('macro task 3 callback'); }, 0); }) console.log('create macro task 2'); setTimeout(() => { console.log('macro task 2 callback'); new Promise(resolve => { console.log('create micro task 3'); resolve(); }).then(() => { console.log('micro task 3 callback'); }) console.log('create macro task 4'); setTimeout(() => { console.log('macro task 4 callback'); }, 0); }, 0); new Promise(resolve => { console.log('create micro task 2'); resolve(); }).then(() => { console.log('micro task 2 callback'); }) console.log('======== main task end ========');
======== main task start ========
create micro task 1
create macro task 2
create micro task 2
======== main task end ========
micro task 1 callback
micro task 2 callback
macro task 2 callback
create micro task 3
create macro task 4
micro task 3 callback
macro task 3 callback
macro task 4 callback
await 表达式会暂停当前 async function 的执行,等待 Promise 处理完成。
在没有 await 的情况下执行 async 函数,它会立即执行,返回一个 Promise 对象,并且,绝不会阻塞后面的语句
async function async1(){ console.log('async1 start') await async2() console.log('async1 end') } async function async2(){ console.log('async2') } console.log('script start') setTimeout(function(){ console.log('setTimeout') },0) async1(); new Promise(function(resolve){ console.log('promise1') resolve(); }).then(function(){ console.log('promise2') }) console.log('script end')
script start
async1 start
async2
promise1
script end
async1 end
promise2
setTimeout
async function t1 () { console.log(1) console.log(2) new Promise( function ( resolve ) { console.log( 'promise3' ) resolve(); } ).then( function () { console.log( 'promise4' ) } ) await new Promise( function ( resolve ) { console.log( 'b' ) resolve(); } ).then( function () { console.log( 't1p' ) } ) console.log(3) console.log(4) new Promise( function ( resolve ) { console.log( 'promise5' ) resolve(); } ).then( function () { console.log( 'promise6' ) } ) } setTimeout( function () { console.log( 'setTimeout' ) }, 0 ) async function t2() { console.log(5) console.log(6) await Promise.resolve().then(() => console.log('t2p')) console.log(7) console.log(8) } t1() new Promise( function ( resolve ) { console.log( 'promise1' ) resolve(); } ).then( function () { console.log( 'promise2' ) } ) t2() console.log('end');
1
2
promise3
b
promise1
5
6
end
promise4
t1p
promise2
t2p
3
4
promise5
7
8
promise6
setTimeout