Understanding Asynchronous JavaScript: Why Your Array Is Empty?

I'm Shubham (@shubhamsinghbundela), I'm a Software Engineer, a Full-stack developer, a tech enthusiast, and a technical writer here on @Hashnode. I have a strong zeal to share my acquired knowledge and I am also willing to learn from others.
const worker = (delay) =>
new Promise((resolve) =>
setTimeout(() => resolve(`Finished ${delay}`), delay)
);
async function run() {
let results = [];
let items = [2, 10, 2];
for (let i = 0; i < items.length; i++) {
const data = await worker(items[i]);
results.push(data);
}
console.log("Final results:", results);
}
run();
The Confusion
Inside the callback →
resultscontains dataOutside the callback →
resultsis still[]
The Real Reason: Asynchronous Execution
The key lies in this line:
setTimeout(...)
setTimeout is asynchronous.
That means:
The
forloop runs immediately.The callback runs later.
JavaScript does NOT wait for it.
How JavaScript Actually Works
JavaScript:
Is single-threaded
Uses the Event Loop
Sends
setTimeoutto Web APIsPushes callback to Callback Queue
Executes it when Call Stack is empty
So your loop finishes before any timeout completes.
Final Takeaway
If you remember just one thing from this blog:
The loop runs synchronously.
setTimeout runs asynchronously.
JavaScript does NOT wait unless you tell it to.




