简体   繁体   English

使 function 调用同步

[英]Make the function call synchronous

function first(){
    console.log("1")
}

function second(){
     new Promise ((resolve,reject)=>{
        setTimeout(function(){
            console.log("2")
            resolve();
        } ,0);

     })  
}

function third(){
    console.log("3")
}

 async function run(){
   
    first();
    await second();
    third();

}

run();

Need to make the function call sync to get final output as 1,2,3 i tried creating the promise and use async await but that didnt help any other way需要使 function 调用同步以获得最终的 output 为 1,2,3 我尝试创建 promise 并使用异步等待,但这对任何其他方式都没有帮助

Pack the setTimeout into a promise and resolve in setTimeout,将 setTimeout 打包成 promise 并在 setTimeout 中解析,

Use async await for that promise in order for that to run consecutively对该 promise 使用 async await 以使其连续运行

 function first() { console.log("1") } function second() { return new Promise(res => { setTimeout(function() { console.log("2"); res() }, 0) }) } function third() { console.log("3") } async function run() { first(); await second() third(); } run();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM