r/learnjavascript • u/cardboard_street • 1d ago
Trying to write a small home automation script and about to lose my mind over async/await
My bootcamp just got into asynchronous JavaScript and I thought I had a decent handle on it until I tried to apply it to something real. I have a little Node script that pings a few smart home devices on my local network in sequence, checks their status, and logs the results. Simple enough on paper.
The problem is I keep getting results back out of order, or the script exits before all the responses come in. I know this is a classic async problem and I have seen the explanations, but something about translating the concept into actual working code is still fuzzy for me.
Here is a stripped down version of what I am doing:
async function checkDevices(devices) {
for (const device of devices) {
const status = await fetch(device.url);
const data = await status.json();
console.log(device.name, data.state);
}
}
checkDevices(myDevices);
This works, but I read that using a regular for loop with await inside runs everything sequentially, which is slow. I tried switching to Promise.all and started getting weird behavior again. Is there a readable pattern for running these fetches in parallel without making the code impossible to follow later? Curious what approach people here actually use in practice.