Open XiaoChengyin opened 4 years ago
async function a1() {
console.log('start')
let a2result = await a2()
console.log(a2result)
let a3result = await a3(a2result)
console.log(a2result)
return a3result
}
// chrome 71
function aa1() {
console.log('start')
return new Promise(resolve => {
a2().then(resolve)
}).then(a2result => {
console.log(a2result)
return new Promise(resolve => {
a3(a2result).then(resolve)
}).then(a3result => {
console.log(a2result)
return new Promise(resolve => {
resolve(a3result)
})
})
})
}
// chrome 72
function aaa3() {
console.log('start')
return Promise.resolve(a2()).then(a2result => {
console.log(a2result)
return Promise.resolve(a3(a2result)).then(a3result => {
console.log(a2result)
return Promise.resolve(a3result)
})
})
}
// Promise.resolve 原理
Promise.resolve = function(value) {
if (value instanceof Promise) return value
return new Promise(resolve => resolve(value))
}
Promise 和 async/await
事件循环和消息队列
消息队列是一个先进先出的队列,队列中存有需要执行的任务。事件循环是指每当主线程任务执行完毕后会从消息队列中取出下一个要执行的任务。
微任务和宏任务
所有异步任务可以分为两类,即宏任务和微任务。微任务的优先级大于宏任务,当宏任务执行完毕后会立即执行微任务队列中的所有任务,直到当前微任务队列为空时才会执行下一个宏任务。
宏任务:
I/O
、setTimeout
、setInterval
、setImmediate
、requestAnimationFrame
。 微任务:process.nextTick
、MutationObserver
、Promise#then/catch/finally
。Promise
和async
函数async/await
只是Promise
的语法糖,原理与Promise
是一样的,所以async
也属于微任务。一个async
函数就可以理解为一个Promise
,await
之前的代码相当于Promise
的回调函数,都是立即执行的同步代码;await
语句相当于Promise
中的子Promise
,父Promise
想要resolve
必须等子Promise
先resolve
才行;await
后面的代码相当于父Promise.then
中的回调函数,即子Promise
resolve
之后才执行父Promise.then
中的代码。举个例子:
输出结果为:
把 async 函数改写成 Promise 能够的到相同的结果
Promise.resolve(p)
与new Promsie((resolve) => resolve(p))
的差异