Name: thunk-loop
Owner: thunks
Description: Asynchronous tasks loop (while (true) { ... }).
Created: 2016-02-26 11:14:15.0
Updated: 2018-03-15 11:21:08.0
Pushed: 2017-06-04 13:39:48.0
Size: 9
Language: JavaScript
GitHub Committers
User | Most Recent Commit | # Commits |
---|
Other Committers
User | Most Recent Commit | # Commits |
---|
Asynchronous tasks loop (while (true) { … }).
Infinite Clock:
t thunk = require('thunks')()
t thunkLoop = require('..')
i = 0
kLoop(function *() {
eld thunk.delay(1000)
= ++i % 60
nsole.log(i)
turn true
unction (_) {
will never reach here.
t 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. If iter
's result is true
, the loop will continue, otherwise the loop will terminate.
Sync function:
i = 1000
kLoop(function () {
--i) return true
rn 'OK'
unction (err, res) {
ole.log(err, res, i) // null, 'OK', 0
Promise:
i = 1000
kLoop(function () {
--i) return Promise.resolve(true)
rn Promise.resolve('OK')
unction (err, res) {
ole.log(err, res, i) // null, 'OK', 0
Generator function:
i = 1000
kLoop(function *() {
ield thunk or promise
--i) return yield thunk(true)
rn yield Promise.resolve('OK')
unction (err, res) {
ole.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 from iter
.
If errorHandle
omit. the exception from iter
will terminate loop:
kLoop(function *() {
w new Error('error!')
unction (err, res) {
ole.log(err.message, ) 'error!'
If errorHandle
return true
. the exception from iter
will ignore and loop will continue:
i = 1000
kLoop(function () {
--i) throw new Error('test')
rn 'OK'
unction (err) {
ole.log(err.message) // 'test'
rn true
unction (err, res) {
ole.log(err, res, i) // null, 'OK', 0
If errorHandle
throw error:
i = 1000
kLoop(function () {
--i) throw new Error('test')
rn 'OK'
unction (err) {
ole.log(err.message) // 'test'
w new Error('errorHandle error')
unction (err, res) {
ole.log(err.message, i) // 'errorHandle error', 999