promise的回调(微任务)总是在同一个事件循环周期内优先于settimeout的回调(宏任务)执行。javascript是单线程语言,通过事件循环机制处理异步操作,同步代码在调用栈中按顺序执行,遇到异步任务时,promise的.then()、.catch()、.finally()回调被放入微任务队列,而settimeout等宏任务则进入宏任务队列。当同步代码执行完毕,事件循环会优先清空微任务队列,之后才处理宏任务。这意味着即使settimeout设置为0ms延迟,其回调也必须等待所有当前微任务执行完后才会执行。理解这一机制有助于写出更可预测、更健壮的异步代码,避免执行顺序问题,优化用户体验和性能。

Promise的回调(微任务)总是在同一个事件循环周期内,优先于
setTimeout

要深入理解Promise与
setTimeout
当你的代码跑起来,首先会进入“调用栈”(Call Stack),同步代码在这里按部就班地执行。一旦遇到异步任务,比如一个
setTimeout
Promise
.then()

setTimeout
而
Promise
.then()
.catch()
.finally()
MutationObserver

关键点来了:当调用栈清空(所有同步代码执行完毕)后,事件循环会首先且完全地清空微任务队列。也就是说,所有排队的Promise回调会一股脑儿地执行完。只有当微任务队列也空了,事件循环才会从宏任务队列中取出一个任务来执行。执行完这个宏任务后,它会再次检查微任务队列(因为新的宏任务执行过程中可能又产生了新的微任务),如果微任务队列有内容,就再次清空它,然后才进入下一个宏任务的循环。
所以,通常情况下,即便你把
setTimeout(..., 0)
Promise.resolve().then(...)
setTimeout
说实话,刚开始接触JavaScript异步,我也会被
setTimeout(fn, 0)
Promise.resolve().then(fn)
想象一下,你正在做一个复杂的动画或者数据处理。如果你不理解事件循环,你可能会不小心写出阻塞主线程的代码,导致页面卡顿、用户体验极差。比如,一个计算量巨大的循环,如果你把它放在同步代码里,浏览器就直接“假死”了。但如果你能巧妙地利用
setTimeout(..., 0)
再比如,你在处理一些DOM操作。你可能希望在DOM结构完全更新之后,再去测量某个元素的高度。这时候,你用
Promise.resolve().then()
requestAnimationFrame
setTimeout(..., 0)
理解了基础规则,我们来看看一些更“烧脑”的场景,这正是我们常会掉坑的地方。
首先要明确,
new Promise((resolve) => { console.log('Promise constructor'); resolve(); })Promise constructor
.then()
.catch()
.finally()
考虑下面这个例子,它能很好地展示两者的交错:
console.log('Start'); // 1. 同步执行
setTimeout(() => {
console.log('setTimeout 1'); // 6. 第一个宏任务
Promise.resolve().then(() => {
console.log('Promise inside setTimeout'); // 7. setTimeout 1 执行后产生的微任务
});
}, 0);
new Promise(resolve => {
console.log('Promise constructor'); // 2. 同步执行
resolve();
}).then(() => {
console.log('Promise then 1'); // 4. 第一个微任务
});
setTimeout(() => {
console.log('setTimeout 2'); // 8. 第二个宏任务
}, 0);
console.log('End'); // 3. 同步执行这段代码的输出顺序会是:
Start Promise constructor End Promise then 1 setTimeout 1 Promise inside setTimeout setTimeout 2
我们来一步步拆解:
console.log('Start')setTimeout 1
new Promise
console.log('Promise constructor')resolve()
Promise then 1
.then()
console.log('End')至此,所有同步代码执行完毕,调用栈清空。事件循环开始工作:
Promise then 1
setTimeout 1
setTimeout 1
Promise.resolve().then()
.then()
setTimeout 1
Promise inside setTimeout
setTimeout 2
通过这个例子,我们能清晰地看到,即使
setTimeout
理解了Promise和
setTimeout
延迟UI更新与避免阻塞: 当你需要执行一些计算量较大但又不想阻塞用户界面的操作时,
setTimeout(..., 0)
setTimeout
function processHeavyData() {
// 假设这里有大量计算
let result = 0;
for (let i = 0; i < 100000000; i++) {
result += i;
}
console.log('Heavy data processed:', result);
// 立即更新DOM可能会卡顿
// document.getElementById('status').textContent = '数据处理完成!';
}
// 更好的方式:利用setTimeout给UI更新留出空间
document.getElementById('startButton').addEventListener('click', () => {
document.getElementById('status').textContent = '正在处理数据...';
setTimeout(() => {
processHeavyData();
document.getElementById('status').textContent = '数据处理完成!';
}, 0); // 0ms延迟,但意味着在下一个宏任务周期执行
});微任务批处理与确保回调时机:
Promise.resolve().then()
queueMicrotask()
let batchedUpdates = [];
let isScheduled = false;
function scheduleBatchUpdate(data) {
batchedUpdates.push(data);
if (!isScheduled) {
isScheduled = true;
Promise.resolve().then(() => {
// 在当前微任务队列清空时执行所有收集到的更新
console.log('Processing batched updates:', batchedUpdates);
batchedUpdates = [];
isScheduled = false;
});
}
}
// 模拟多次调用
scheduleBatchUpdate('item A');
scheduleBatchUpdate('item B');
console.log('Sync code continues...');
scheduleBatchUpdate('item C');
// Output: Sync code continues... -> Processing batched updates: ["item A", "item B", "item C"]这里,所有的
scheduleBatchUpdate
优雅的错误重试机制: 结合Promise的链式调用和
setTimeout
function fetchDataWithRetry(url, retries = 3, delay = 1000) {
return new Promise((resolve, reject) => {
fetch(url)
.then(response => {
if (!response.ok) throw new Error('Network response was not ok.');
return response.json();
})
.then(resolve)
.catch(error => {
if (retries > 0) {
console.warn(`Retrying ${url} in ${delay / 1000}s... Attempts left: ${retries - 1}`);
setTimeout(() => {
fetchDataWithRetry(url, retries - 1, delay * 2)
.then(resolve)
.catch(reject);
}, delay);
} else {
reject(new Error(`Failed to fetch ${url} after multiple retries: ${error.message}`));
}
});
});
}
// fetchDataWithRetry('https://api.example.com/data')
// .then(data => console.log('Data fetched:', data))
// .catch(error => console.error('Error:', error.message));在这个例子中,如果
fetch
setTimeout
总的来说,Promise和
setTimeout
setTimeout
以上就是Promise与setTimeout的执行顺序的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号