Asynchronous tasks loop (while (true) { ... }).
Infinite Clock:
const thunk = require('thunks')()
const thunkLoop = require('..')
var i = 0
thunkLoop(function *() {
yield thunk.delay(1000)
i = ++i % 60
console.log(i)
return true
})(function (_) {
// will never reach here.
})
const thunkLoop = require('thunk-loop')
return thunk function. You should run the thunk function because of thunk's lazy evaluation. If iter is infinite, you will not get the last result except error occured.
-
iter
: {Function}, it is your task loop, can be sync or async task. Ifiter
's result istrue
, the loop will continue, otherwise the loop will terminate.Sync function:
var i = 1000 thunkLoop(function () { if (--i) return true return 'OK' })(function (err, res) { console.log(err, res, i) // null, 'OK', 0 })
Promise:
var i = 1000 thunkLoop(function () { if (--i) return Promise.resolve(true) return Promise.resolve('OK') })(function (err, res) { console.log(err, res, i) // null, 'OK', 0 })
Generator function:
var i = 1000 thunkLoop(function *() { // yield thunk or promise if (--i) return yield thunk(true) return yield Promise.resolve('OK') })(function (err, res) { console.log(err, res, i) // null, 'OK', 0 })
-
errorHandle
: {Function}, it is optional, can be sync or async function. It is used to catch the exception fromiter
.If
errorHandle
omit. the exception fromiter
will terminate loop:thunkLoop(function *() { throw new Error('error!') })(function (err, res) { console.log(err.message, ) 'error!' })
If
errorHandle
returntrue
. the exception fromiter
will ignore and loop will continue:var i = 1000 thunkLoop(function () { if (--i) throw new Error('test') return 'OK' }, function (err) { console.log(err.message) // 'test' return true })(function (err, res) { console.log(err, res, i) // null, 'OK', 0 })
If
errorHandle
throw error:var i = 1000 thunkLoop(function () { if (--i) throw new Error('test') return 'OK' }, function (err) { console.log(err.message) // 'test' throw new Error('errorHandle error') })(function (err, res) { console.log(err.message, i) // 'errorHandle error', 999 })