Node.js中使用setTimeout报错:setTimeout is not a function 求助
解决Node.js中
timers/promises导入setTimeout报错问题 问题原因
你遇到的TypeError: setTimeout is not a function是因为错误使用了默认导入,timers/promises模块中的setTimeout是命名导出,而非默认导出。直接默认导入会得到一个包含该函数的对象,而非函数本身,调用自然会报错。
解决方案
1. 修正导入语句
将默认导入改为命名导入,这是最直接的解决方式:
import { setTimeout } from 'timers/promises' console.log('It will be printed 1-st'); async function newStyleDelay() { await setTimeout(5000); console.log('It will be printed 3-rd with delay'); } newStyleDelay(); console.log('It will be printed 2-nd');
2. 确认Node.js版本兼容性
timers/promises模块在Node.js 15.0.0及以上版本才稳定可用,如果你的Node.js版本低于这个版本,需要升级Node.js,或者改用传统setTimeout结合Promise封装的替代方案:
// 手动封装Promise版setTimeout const setTimeoutPromise = (delay) => new Promise(resolve => setTimeout(resolve, delay)); console.log('It will be printed 1-st'); async function newStyleDelay() { await setTimeoutPromise(5000); console.log('It will be printed 3-rd with delay'); } newStyleDelay(); console.log('It will be printed 2-nd');
内容的提问来源于stack exchange,提问作者GP.
相关产品推荐
相关产品推荐

