我知道
setTimeout
是一个异步运行的 API,我想同步运行它。像下面这样使用 async/await
应该先打印 bla bla
但我先得到 bla
.
async function testing(){
console.log("testing function has been triggered");
await setTimeout(function () {
console.log("bla bla")
}, 4200)
console.log("bla");
}
setTimeout
不返回 Promise
,所以你不能 await
它。
您可以将
setTimeout
包装在一个函数中,该函数返回一个 Promise
,一旦计时器到期,该函数就会完成。你可以await
这个包装函数。
function createCustomTimeout(seconds) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('bla bla');
resolve();
}, seconds * 1000);
});
}
async function testing() {
console.log('testing function has been triggered');
await createCustomTimeout(4);
console.log('bla');
}
testing();
async function testing(){
console.log("testing function has been triggered");
console.log(await printFunction());
console.log("bla");
}
function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
const printFunction = async () => {
await timeout(4200);
return "bla bla"
}
testing();
如果解决了您的问题,请支持并回答,谢谢。
从
setTimeout
导入node:timers/promises
:
import {setTimeout} from 'node:timers/promises'
const res = await setTimeout(1000, 'result')
console.log(res) // Prints 'result' after 1000ms