1.0.7 • Published 7 years ago

thunk-loop v1.0.7

Weekly downloads
3
License
MIT
Repository
github
Last release
7 years ago

thunk-loop

Asynchronous tasks loop (while (true) { ... }).

NPM version Build Status Downloads

thunks

Demo

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.
})

API

const thunkLoop = require('thunk-loop')

thunkLoop(iter, errorHandle)

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:

    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 from iter.

    If errorHandle omit. the exception from iter will terminate loop:

    thunkLoop(function *() {
      throw new Error('error!')
    })(function (err, res) {
      console.log(err.message, ) 'error!'
    })

    If errorHandle return true. the exception from iter 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
    })
1.0.7

7 years ago

1.0.6

8 years ago

1.0.5

8 years ago

1.0.4

8 years ago

1.0.2

8 years ago

1.0.1

8 years ago

1.0.0

8 years ago

0.1.0

8 years ago