I am building an app that must poll remote devices (generator fn sendRequests()
) every 2 seconds.
What's the right way to call the generator fn using setInterval, which isn't a generator and doesn't yield
function * sendRequests() {
// multiple remote async requests are sent
}
var timer = setInterval(() => {
// yield sendRequests()
}, 2000)
The problem with yielding from the
setInterval
callback is thatyield
can only yield to the generatorfunction*
that immediately contains it. Therefore, you can'tyield
from a callback.What you can do from a callback is resolve a Promise, which your generator function can
yield
:The problem with that is a Promise can only be settled once. Therefore, calling
resolve
every 2000ms won't do anything beyond the first call.What you can do instead is call
setTimeout
repeatedly, in a while loop:The new
for-await-of
syntax has been available since Node v9.2, and can be used in Node v10 or later without any flags.Since AdonisJS uses co() under the hood, I used @Bergi suggestion of wrapping in co()