Search code examples
javascriptasync-awaites6-promise

How to make async call one by one with async/await?


I have two simple async functions: First:

const first = async () => {
    setTimeout(() => {
        console.log(1)
    },2000);
}

Second:

const second = async () => {
    console.log(2);
}

I'm trying to hold second function until first is done. My code:

router.post('/', errorHandler(async (req, res) => {
    try {

        await first();
        await second();

    } catch (err) {
        console.log(err);
    }
})
);

But the second function executing first. How do I have to use await to get what I want? Thank you in advance!


Solution

  • The problem is it has no way to know when your code is done. If you change the first function to something like the following it should work.

    const first = () => {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                console.log(1);
                resolve();
            },2000);
        });
    }
    

    Basically what this is doing is returning a promise that will resolve after your timeout is done. That way your await will wait until the resolve function gets called.

    You could also do something like the following to convert setTimeout to a promise.

    const timeout = (ms) => {
        return new Promise((resolve, reject) => {
            setTimeout(() => resolve(), ms);
        });
    }
    
    const first = async () => {
        await timeout(2000);
        console.log(1);
    }
    

    But the biggest problem is you are trying to combine callbacks and promises (await). So at some point you have to convert that callback (setTimeout) into a promise so you can await it.