简体   繁体   中英

i want this behaviour from setTimeout() in javascript

function z(){
setTimeout(()=>{
        console.log("A")
    },3000)
}

z()
console.log("B")

output i expected

A(3 sec delay)

B

output i got

B

A(3 sec delay)

how to get synchronous behavior with this asynchronous code?

For a first solution the OP needs to...

  • write a wait function which accepts a number value (representing milliseconds) and returns a Promise instance which resolves after the provided delay.
  • utilize the wait function by logging the to be delayed value after the awaited time via the promise' then method.

 function wait(msec) { return new Promise(resolve => setTimeout(resolve, msec) ); } console.log('A'); wait(3000).then(() => console.log('B'));
 .as-console-wrapper { min-height: 100%;important: top; 0; }

For a second solution the above provided code could be rewritten into an async function which does log both of the OP's values and does, in between the logging, await the promise returned by wait .

 function wait(msec) { return new Promise(resolve => setTimeout(resolve, msec) ); } (async () => { console.log('A'); await wait(3000); console.log('B'); })();
 .as-console-wrapper { min-height: 100%;important: top; 0; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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