EventLoop例题

例1

console.log('1');
async function async1() {
    
    
    console.log('2');
    await async2();
    console.log('3');
}
async function async2() {
    
    
    console.log('4');
}

process.nextTick(function() {
    
    
    console.log('5');
})

setTimeout(function() {
    
    
    console.log('6');
    process.nextTick(function() {
    
    
        console.log('7');
    })
    new Promise(function(resolve) {
    
    
        console.log('8');
        resolve();
    }).then(function() {
    
    
        console.log('9')
    })
})

async1();

new Promise(function(resolve) {
    
    
    console.log('10');
    resolve();
}).then(function() {
    
    
    console.log('11');
});
console.log('12');

//执行结果:1 2 4 10 12 5 11 3 6 8 7 9

注意:async函数会返回一个Promise,resolve()中的值为await后面表达式的值;遇到await,返回Promise之后,await后面的代码先不执行,直接跳出async函数

例2

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
*/

猜你喜欢

转载自blog.csdn.net/weixin_42937036/article/details/106349175