nodejs async/await placement for multiple functions

Q1

No, you can’t remove await inside the delete_callback.
And you also need to add await in do_stuff function when calling delete_callback like following code.

The following code will succeed

async function delete_callback(msg) {
    await Models.Callbacks.deleteOne({chat_id: msg.chat.id, from_id: msg.from.id});
}

async function do_stuff(msg) {
    try {
        await some_other_async_function(msg);
        // add await here
        await delete_callback(msg);
    }
    catch(err) {
        handleError(err);
    }
}

Q2

You will trigger the function. But you need to add await or return inside the delete_callback. Otherwise, the delete_callback function will finish immediately.

async function delete_callback(msg) {
    return Models.Callbacks.deleteOne({chat_id: msg.chat.id, from_id: msg.from.id});
}

async function do_stuff(msg) {
    try {
        await some_other_async_function(msg);
        await delete_callback(msg);
    }
    catch(err) {
        handleError(err);
    }
}

Here is example when you don’t add await or return in test() function.
This test function is your delete_callback function.

function b() {
    return new Promise((resolve, reject) =>{
        setTimeout(() => {
            console.log("doing b");
            resolve();
        }, 5000)
    })
}

async function test () {
    b()
}

async function main() {
    try {
        let a = await test()
        console.log("a: ", a);
    } catch (error) {
        console.log(error);
    }
    console.log("done");
}

main()

Q3

If delete_callback is not async function, then it’s normal function which don’t throw error.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top