假设我有这样的代码:
console.log(1);
console.log(2);
setTimeout(() => console.log("Callback fired"),2000);
console.log(3);
console.log(4);
我想要的是在控制台记录1和2,然后等待2秒来记录"Callback触发"然后继续。
我确实尝试过使用promise,但这也不起作用,或者可能我做错了
必须使用异步代码。下面是一个例子:
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
(async () => {
//here your code is async
console.log(1);
console.log(2);
await sleep(2000); // sleep for 2 secs
console.log("timeout over");
console.log(3);
console.log(4);
})();
您可以在主逻辑中setTimeout
和await
的回调中resolve
和Promise
,如下所示。
(async() => {
console.log(1);
console.log(2);
await awaitThenLog("Callback fired", 2000);
console.log(3);
console.log(4);
})();
async function awaitThenLog(message, delay) {
return new Promise((resolve) => {
setTimeout(() => {
console.log(message);
resolve();
}, delay);
});
}