Monday, 9 December 2019

Retry loop with a pause between attempts

Hi,So I'm very new to node so please be kind.I'm trying to better manage a device which drops the odd ping and reconnects a second or two later. Basically, before sending data I'd like to check the state of the device. If the device is unavailable, I'd like to pause for a couple of seconds and recheck. Obviously this can't go on forever so I need to give up after a certain number of attempts.In languages I'm more familiar with this is easy but with node I can't get this to work. Here's what I have:const waitForDevice = async (device) => { let count = 0; while (device.state !== 'active' && count <= 6 ) { count++; await setTimeout(() => { }, 2000); } if (count > 6) console.log(`The device is not available.`); return; } //Main processing await waitForDevice(device); doStuff(); What I'm seeing is it loops through 6 times in a fraction of a second.I've changed things countless times and lost track of which blogs I've read and tried. Could someone give me pointers?

Submitted December 09, 2019 at 09:51PM by kiwi_cam

No comments:

Post a Comment