难点1:遇到Promise.resolve()/Promise.reject()就相当于平时使用时写在{}里面的内容,功能只有传参和改变promise对象的状态,如果在他们内部执行代码,也是同步代码
难点2:当await遇到普通函数(非promise/setTimeout)的时候,不阻塞的时候也是按顺序执行的同步代码
难点3:await遇到promise函数的时候,如果resolve,后面的同步代码都会包裹在then(res => { 这里 })进入微队列等待执行
console.log('0');
setTimeout(() => {
console.log('1');
}, 1 * 2000);
Promise.resolve()
.then(function() {
console.log('2');
}).then(function() {
console.log('3');
});
async function foo() {
await bar()
console.log('4')
}
foo()
async function errorFunc () {
try {
await Promise.reject('5')
} catch(e) {
console.log('6')
}
console.log('7');
return Promise.resolve('8')
}
errorFunc().then(res => console.log(9))
function bar() {
console.log('10')
}
console.log('11');
// 0 10 11 2 4 6 7 3 9 1
在原本的基础上改变了一点输出,这样的输出可能会更好理解一点,如果还是不好理解可以把这几个块分开,比如把errorFunc函数先注释一下,分块理解,就会好懂一点
console.log('0');
setTimeout(() => {
console.log('1');
}, 1 * 2000);
Promise.resolve()
.then(function() {
console.log('2');
}).then(function() {
console.log('3');
});
async function foo() {
await Promise.resolve('resolve').then(res => console.log(res))
await bar()
console.log('4')
Promise.resolve('xxx').then(res => console.log(res))
}
foo()
async function errorFunc () {
try {
await Promise.reject(console.log('5'))
} catch(e) {
console.log('6')
}
console.log('7');
return Promise.resolve(console.log('8'))
}
errorFunc().then(res => console.log('9'))
function bar() {
console.log('10')
}
console.log('11');
// 0 5 11 2 resolve 6 7 8 3 10 4 xxx 9 1