Search code examples
javascriptfunctionasynchronoussynchronous

how console.log1234 in synchronous way


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();


Solution

  • 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.