The ‘Async’ Deception: Not All JavaScript ‘Async’ Functions Behave as Expected

Ibraheem Z. Abu Kaff
2 min readJan 28, 2024

JavaScript’s async/await has revolutionized asynchronous programming, but does it always do what we think it does?

Part 1: The Deceptive Simplicity of Async Functions.

Async/Await Implementation:

console.log('Before async function');

async function nonConcurrentAsyncFunction() {
console.log('Inside async function');
}

nonConcurrentAsyncFunction();

console.log('After async function');

Execution Result:

Before async function
Inside async function
After async function

Explanation(WHY!):

The implementation runs synchronously, debunking the myth that async always means asynchronous execution. The key takeaway is that the async function, without await in it, behaves just like a regular function! 🥸.

Part 2: The Hidden Pause in Async/Await.

Async/Await Implementation:

console.log('Before async function with await');

async function pausingAsyncFunction() {
console.log('Start of async function');
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('End of async function');
}

pausingAsyncFunction();

console.log('After async function with await');

Execution Result:

Before async function with await
Start of async function
After async function with await
// (1-second pause)
End of async function

Explanation (WHY!):

This part demonstrates the non-blocking nature introduced by await. The await keyword causes the function to pause, but crucially, it does not block the JavaScript runtime (the remaining code that lives outside that async method will continue to execute normally). This is evident from the execution results where `After async function with await`, is logged before the function completes its pause.

This reveals the subtle yet powerful impact of await on asynchronous programming, highlighting its role in facilitating non-blocking behavior within the async function it's used in.

Summary and Conclusion:

This exploration into async/await reveals that its behavior is not as straightforward as many believe. Understanding the nuances of async/await, and recognizing when is truly asynchronous, is vital for mastering JavaScript's asynchronous programming paradigm. This knowledge empowers developers to write more efficient and reliable code, unraveling the surprising truths of async/await.

--

--

Ibraheem Z. Abu Kaff

Dubai-based Syrian Software Engineer, skilled in: #php #python #Node.js #django #laravel #mongodb #redis #docker #rest #k8s #microservices. ibraheem-abukaff.com