前言

1
2
3
4
5
6
7
8
9
10
11
12
13

setTimeout(() => {
console.log('timeout');
}, 0);

Promise.resolve().then(data => {
console.log('then');
});

console.log('start');

// start => then => timeout

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
setTimeout(() => {
console.log('timeout1');
Promise.resolve().then(data => {
console.log('then1');
});
}, 0);

Promise.resolve().then(data => {
console.log('then2');
setTimeout(() => {
console.log('timeout2');
}, 0);
});

// then2 => timeout1 => then1 => timeout2

1
2
3
4
5
6
7
8
9
10
11
12
13
const p = new Promise(function(resolve, reject){
reject();
resolve();
});
p.then(function() {
console.log('成功');
}, function() {
console.log('失败');
});

// 失败
// 只会打印失败,因为Promise的状态只会变化一次。

1
2
3
4
5
6
7
8
9
10
11
12
13
const promise = new Promise((resolve, reject) => {
console.log(1);
resolve();
console.log(2);
});
promise.then(() => {
console.log(3);
});

// 1, 2, 3
// new Promise传入的函数是同步代码,立刻就会被执行,所以会打印出1和2,
// Promise.then是微任务,当代码自行结束,会清空微任务队列,打印出3.

1
2
3
4
5
6
7
Promise.resolve(1)
.then(res => 2)
.catch(err => 3)
.then(res => console.log(res));

// 2

1
2
3
4
5
6
7
8
9
Promise.resolve(1)
.then((x) => x + 1)
.then(x => { throw new Error('My Error')})
.catch(() => 1)
.then(x => x + 1)
.then(x => console.log(x))
.catch(console.error);

// 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
setTimeout(function(){
console.log(1)
},0)
new Promise(function executor(resolve) {
console.log(2)
for(var j = 0;j<100;j++){
j=99&&resolve()
}
console.log(3)
}).then(function(){
console.log(4)
})
console.log(5)

// 2 3 5 4 1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
async function async1() {
console.log('async1 start'); // 2
await async2();
};

async function async2() {
console.log('async2'); // 3
}

console.log('script start'); // 1

setTimeout(function() {
console.log('setTimeout'); // 7
}, 0);

async1();

new Promise(function(resolve) {
console.log('promise1'); // 4
resolve();
}).then(function() {
console.log('promise2'); // 6
});

console.log('script end2'); // 5


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
async function async1() {
console.log('async1 start') // 2
await async2() // await后面的函数,相当于new Promise传入的函数是立即执行的
console.log('async1 end') // 5 await下面的代码在await成功之后执行,相当于Promise.then,是一个微任务,不过是语法糖让这行代码看起来是同步的,其实不是的
}

async function async2() {
console.log('async2') // 3
}

console.log('script start') // 1
setTimeout(function() {
console.log('setTimeout') // 7
}, 0)

async1();

new Promise( function( resolve ) {
console.log('promise1') // 4
resolve();
}).then( function() {
console.log('promise2') // 6
})