好吧,EventLoop

详情请参考该篇博文

几个问题:

下面这两种代码有什么不同?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
new Promise((resolve, reject) => {
resolve(1);
}).then(n => {
console.log(n, 'step1');
new Promise(resolve => {
resolve(2);
}).then(n => {
console.log(n, 'step2');
}).then(n => {
console.log('step4');
})
}).then(n => {
console.log(n, 'step3');
})

上面这种代码输出:1 step1换行2 step2换行undefined step3换行step4

1
2
3
4
5
6
7
8
9
10
11
12
13
14
new Promise((resolve, reject) => {
resolve(1);
}).then(n => {
console.log(n, 'step1');
return new Promise(resolve => {
resolve(2);
}).then(n => {
console.log(n, 'step2');
}).then(n => {
console.log('step4');
})
}).then(n => {
console.log(n, 'step3');
})

上面这种代码输出:1 step1 换行 2 step2 换行 step4 换行 undefined step3

接下来看一个async和promise组合使用的问题:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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');

对于遇到了async的情况,我们可以把它转化成下面这样在进行分析:

1
2
3
4
5
6
7
// before
await async2();

// after
Promise.resolve(async2()).then(() => {
console.log('async1 end');
})

对于上面这道题目的分析,详情参见Yancey’Blog