昨天是個緊張但是美好的一天刽严,學(xué)到了很多東西,也刺激了我的學(xué)習(xí)熱情避凝。舞萄。。
今天是個緊張但是美好的一天管削,我在這里寫下了這篇博客倒脓。。含思。
我們今天討論一下崎弃,promise和settimeout到底誰執(zhí)行的速度快?
測試?yán)笾σ唬海ㄏ仍谀X袋里想想含潘,在看答案哦)
setTimeout(() => {
console.log(1)
});
const a = new Promise((resolve,reject)=>{
console.log(2);
resolve(3)
})
setTimeout(() => {
console.log(4)
});
const b = new Promise((resolve,reject)=>{
console.log(5)
resolve(6)
})
b.then(value=>console.log(value))
a.then(value=>console.log(value))
答案:
2
5
6
3
1
4
測試?yán)笾Χ?/strong>
setTimeout(function(){
console.log('定時器開始啦')
});
new Promise(function(resolve){
console.log('馬上執(zhí)行for循環(huán)啦');
for(var i = 0; i < 10000; i++){
i == 99 && resolve();
}
}).then(function(){
console.log('執(zhí)行then函數(shù)啦')
});
console.log('代碼執(zhí)行結(jié)束');
答案:
馬上執(zhí)行for循環(huán)啦
代碼執(zhí)行結(jié)束
執(zhí)行then函數(shù)啦
定時器開始啦
測試?yán)笾θ?/strong>
console.log('1');
setTimeout(function() {
console.log('2');
process.nextTick(function() {
console.log('3');
})
new Promise(function(resolve) {
console.log('4');
resolve();
}).then(function() {
console.log('5')
})
})
process.nextTick(function() {
console.log('6');
})
new Promise(function(resolve) {
console.log('7');
resolve();
}).then(function() {
console.log('8')
})
setTimeout(function() {
console.log('9');
process.nextTick(function() {
console.log('10');
})
new Promise(function(resolve) {
console.log('11');
resolve();
}).then(function() {
console.log('12')
})
})
答案:
1
7
6
8
2
4
9
11
3
10
5
12
其實從答案中不難發(fā)現(xiàn)幾個規(guī)律饲做,
- promise和process.nextTick在程序中是先于settimtout執(zhí)行的;
- 在promise和process.nextTick里面的console語句的執(zhí)行速度是三個中最快遏弱,它與promise和process.nextTick執(zhí)行的順序無關(guān)盆均,只與promise和process.nextTick聲明的順序有關(guān);
好了漱逸,以上的結(jié)果也只是表象缀踪,想知道具體內(nèi)部實現(xiàn)原理我們還是需要對JavaScript的同步任務(wù)和異步任務(wù)進行深入了解了。
關(guān)于這點有一個很好的博客推薦大家:https://juejin.im/post/59e85eebf265da430d571f89