Issue
I am creating a parent-child system, with a Raspberry Pi 3 as the parent, and a series of Arduinos as the children.
The parent's primary activities are reading/writing data to the children over I2C, hosting a webserver, storing/recalling data from a Mongo DB Client, and reading/writing to GPIO.
What I'm looking for is a way to have my "main" chunk of code forever, similarly to how the code in an Arduino's loop() function works.
I know while(true) loops are a no-no, but I'm wary of using setTimeout to trigger this repeated execution because my code have very significantly different execution time depending on I2C and Database stuff.
Will a library like forever or PM2 serve me here?
Solution
First of all, both forever and PM2 are CLIs and made to keep processes alive by automatically restarting them when needed. If I understood that correctly, you want to repeat a chunk of code and not a process, so here's a solution on how to do that considering that you use a lot of asynchronous code:
async function loop() {
/*
Do everything you want to do in one iteration inside this function
and use the `await` keyword to wait for Promises to resolve. If you use
libraries that don't support Promises yet, look for a wrapper that uses
them (often called "xy-as-promised") or use `require('util').promisify()`.
*/
}
async function startLoop() {
while(true) await loop()
}
startLoop()
Answered By - Niklas Higi Answer Checked By - Katrina (WPSolving Volunteer)