DEV Community

Fransisco Wijaya
Fransisco Wijaya

Posted on • Updated on

Async/Await - Pause what?

Confused over async/await?
Here's some TLDR; info about it.

Await only pauses its parent Async function

const messages = return new Promise((resolve), () => {
    setTimeout(() => {
        resolve(["Hey", "Good day"]);
    }, 5000);
});

async function sendMessages() { // <-- Await only pauses this function
    console.log("Sending message...");
    console.log("Message sent: ", await messages); // <-- If await reached, it executes code outside this async function, and pause this async function
}

// Let's proof it
console.log("Start");
sendMessages();
console.log("End");

// Output:

// Start
// Sending message...                  <-- sendMessage() function
// End                                 <-- Proof, await makes execution continue outside its function
// Message sent: ["Hey", "Good day"]   <-- After 5 seconds, this appears

This proof that await jumps the code execution outside its async function whenever called.
You can see that await only pauses its parent async function, not the entire code outside that function.
See console.log("End") called before finishing the await.

But I don't want it, I want my code executed orderly / step by step / synchronously!

I got you, here's to solve that:

const messages = return new Promise((resolve), () => {
    setTimeout(() => {
        resolve(["Hey", "Good day"]);
    }, 5000);
});

async function sendMessages() {
    console.log("Sending message...");
    console.log("Message sent: ", await messages);
}

// -- Old Code
// console.log("Start");
// sendMessages();
// console.log("End");

// -- New Code
async function log() {
    console.log("Start");
    await sendMessages();
    console.log("End");
}
log();

// Output:
// Start
// Sending message...                  <-- sendMessage() function
// Message sent: ["Hey", "Good day"]   <-- After 5 seconds, this appears
// End

What did I do?
Wrap everything to be executed orderly inside an async function, add await to a "promising" function.

Top comments (0)