如何在同步模式下调用 javascript 函数



我有下面的javascript代码,然后我想同步调用它们,例如1,2,3,4。 请提出解决方案。我可以在其中使用asyncawait关键字吗?

function first(){
setTimeout(function(){
console.log('1');
},500)
}
function second(){
console.log('2');
}
function third(){
setTimeout(function(){
console.log('3');
},502)
}
function four(){
setTimeout(function(){
console.log('4');
},501)
}
first();
second();
third();
four();

如果你想能够使用 async/await,你唯一需要的就是承诺(当然还有对 async/await 的支持(。

因此,根据您的示例,下面的解决方案应该有效。

function first() {
return new Promise((resolve, reject) => setTimeout(() => {
console.log('1');
resolve();
},500)
}
(async () => {
await first();
})()

最新更新