nextMicroTask()
function nextMicroTask<T, R>(fn?): Promise<void | R>;
Defined in: async/nextMicroTask.ts:30
将函数推迟到下一个微任务队列执行 使用Promise.resolve()实现,确保函数在当前同步代码执行完成后、DOM更新前执行
Type Parameters
| Type Parameter | Default type | Description |
|---|---|---|
T | void | 回调函数中this的类型 |
R | void | 回调函数的返回值类型 |
Parameters
| Parameter | Type | Description |
|---|---|---|
fn? | (this) => R | 要推迟执行的函数,可选 |
Returns
Promise<void | R>
解析为回调函数返回值的Promise,若回调抛出错误则Promise会被拒绝 Note: 基于微任务队列实现,执行时机早于setTimeout(fn, 0)等宏任务
Examples
// 基础用法
nextMicroTask(() => {
console.log('在当前同步代码后执行');
});
// 带返回值和async/await
async function example() {
await nextMicroTask(() => '执行完成');
console.log('Promise已解析');
}
// 无回调函数(仅获取下一个微任务的Promise)
async function delay() {
await nextMicroTask();
console.log('下一个微任务');
}