下麵代碼中,setTimeout(fn, 0)在下一輪“事件迴圈”開始時執行,Promise.resolve()在本輪“事件迴圈”結束時執行,console.log('one')則是立即執行,因此最先輸出。 下麵代碼中,setTimeout(fn, 0)在下一輪“事件迴圈”開始時執行,Promise ...
//Promise延時順序執行
var waitOne = new Promise(function(resolve, reject) { setTimeout(function(){ resolve(1)}, 1000); }); var waitSecond = new Promise(function(resolve, reject) { setTimeout(function(){ resolve(1)}, 1000); }); waitOne.then(function() { console.log("Hello"); // 1秒後輸出"Hello" return new Promise(function(resolve, reject) { setTimeout(function(){ resolve(1)}, 1000); }); }).then(function() { console.log("Hi"); // 2秒後輸出"Hi" });
new Promise(function(resolve , reject) { resolve(1); }).then(function(val) { console.log(val); return new Promise(function(resolve , reject) { resolve(2); }); }).then(function(val) { console.log(val); return new Promise(function(resolve , reject) { resolve(3); }); }).then(function(val) { console.log(val); return new Promise(function(resolve , reject) { resolve(4); }); }).then(function(val) { console.log(val); }); //輸出: // 1 // 2 // 3 // 4
下麵代碼中,setTimeout(fn, 0)在下一輪“事件迴圈”開始時執行,Promise.resolve()在本輪“事件迴圈”結束時執行,console.log('one')則是立即執行,因此最先輸出。
setTimeout(function () { console.log('three'); }, 0); Promise.resolve().then(function () { console.log('two'); }); console.log('one');