-2

How can I console 1234 in this function. using await or async. Now it logs 1243. It should wait before the 3 then log the 4.

    function Call(){
     console.log('1');
     console.log('2');
     setTimeout(()=>console.log('3'),1000);
     console.log('4');
    }
    Call();
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Akif Anvar
  • 42
  • 4
  • 1
    Does this answer your question? [How to make a promise from setTimeout](https://stackoverflow.com/questions/22707475/how-to-make-a-promise-from-settimeout). Then all you need to do is await the third log. – evolutionxbox Dec 08 '21 at 17:31
  • 1
    "fix this" is not an appropriate way to talk to people here. – Andy Dec 08 '21 at 17:34
  • Also please note that using async/await does not make the code synchronous. – evolutionxbox Dec 08 '21 at 17:36
  • I suspect English is your second (or third, or fourth) language, but so you know, saying "fix this" to people is very rude in every English-speaking culture I've experienced. (It **might** be okay for a boss talking to an employee, but even then, it's a bit harsh; and that's not at all the situation here.) Instead, ask *how* to fix it: "How do I fix this?" – T.J. Crowder Dec 08 '21 at 17:39

1 Answers1

1

As suggested in the comments, the key here is to create a promise-based setTimeout as described here:

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

Then make your function an async function and await the timeout:

async function call(){
    console.log('1');
    console.log('2');
    await delay(1000);
    console.log('3');
    console.log('4');
}
call();

Normally, you want to handle errors, but we know the above can't throw any, so...

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

async function call(){
    console.log('1');
    console.log('2');
    await delay(1000);
    console.log('3');
    console.log('4');
}
call();

how console.log1234 in synchronous way

Note that the above makes the logic in the function synchronous, but the code does not execute synchronously. call returns as of the await, and then resumes later when the timer fires and settles the promise.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875