题目背景:分享@洛千陨 珍藏题
const p1 = () => (new Promise((resolve, reject) => {
console.log(1);
let p2 = new Promise((resolve, reject) => {
console.log(2);
const timeOut1 = setTimeout(() => {
console.log(3);
resolve(4);
}, 0)
resolve(5);
});
resolve(6);
p2.then((arg) => {
console.log(arg);
});
}));
const timeOut2 = setTimeout(() => {
console.log(8);
const p3 = new Promise(reject => {
reject(9);
}).then(res => {
console.log(res)
})
}, 0)
p1().then((arg) => {
console.log(arg);
});
console.log(10);
输出结果:1 2 10 5 6 8 9 3
输出结果分析
思路:同步->异步
宏任务队列
:8 9 3 4
(8-9这一块都是属于setTimeout里面的,下一轮 Event Loop再执行;resolve(5)后不输出4)
微任务队列
:5 6
(为什么先5后6, 因为在p2定义的时候会执行promise内部的代码, resolve(5)时有下面p2.then接收就会打印5)
JS主线程-同步代码
:1 2 10
注意点
class Scheduler {
constructor(max) {
this.max = max
this.count = 0
this.queue = new Array()
}
async add(promiseCreator) {
if (this.count >= this.max) {
await new Promise((resolve, reject) => {
this.queue.push(resolve)
})
}
this.count++
const res = await promiseCreator()
this.count--
if (this.queue.length) {
this.queue.shift()()
}
console.log('res: ', res)
return res
}
}
const timeout = (time) => new Promise(resolve => {
console.log('100')
setTimeout(resolve, time)
})
const scheduler = new Scheduler(2)
const addTask = (time, order) => {
scheduler.add(() => timeout(time)).then(() => {console.log(order); return 'timeout'})
}
addTask(1000, '1')
addTask(500, '2')
addTask(300, '3')
addTask(400, '4')
输出结果:
100
100
res: undefined
100
2
res: undefined
100
3
res: undefined
1
res: undefined
4
输出结果分析
先打印2个'100'
res: undefined
;打印下一个'100'
再return res打印'2'
res: undefined
;打印下一个'100'
再return res打印'3'
res: undefined
;打印'1'
;res: undefined
;打印'4'
;可参考我的另外一篇博客:ECMAScript 6 Promise - Promise