@joshwillik/task

async function++

Stats

stars 🌟issues ⚠️updated 🛠created 🐣size 🏋️‍♀️
Minified + gzip package size for @joshwillik/task in KB

Readme

Installation

npm install @joshwillik/task

Usage

const task = require('@joshwillik/task')
const fs = require('fs')
const builder = require('./some_fake_module.js')

// wait/continue
task(async function() {
  let build_job = builder.start()
  console.log(`Starting build`)
  build_job.on('built', () => this.continue())
  await this.wait()
  console.log('Build finished')
  build_job.on('uploaded', () => this.continue())
  await this.wait()
  console.log('Upload finished')
  build_job.on('verified', content_sum => this.continue(content_sum))
  let content_sum = await this.wait()
  console.log(`Verified built image: ${content_sum}`)
}).then(() => {
  console.log('task done')
})

// finally
task(async function(){
  let scratch_dir = '/tmp/scratch-dir'
  fs.mkdir(scratch_dir, err => {
    if (err) {
      this.throw(e)
    } else {
      this.continue()
    }
  })
  // altertatively, you can do this instead:
  // fs.mkdir(scratch_dir, this.continue_cb)
  await this.wait()
  // will always run at the end of the task, even if something throws
  this.finally(() => fs.rmdir(scratch_dir))
  // as proven by this code which randomly throws
  if (Math.round(Math.random())) {
    console.log('success')
  } else {
    throw new Error('failed :(')
  }
}).then(() => {
  console.log('task done')
}).catch(err => {
  console.log('task failed, but scratch_dir is still gone')
})

// sleep
task(async function(){
  console.log('before', new Date())
  await task.sleep(1e3)
  console.log('after', new Date())
}).then(() => {
  console.log('task done')
})

API

this.wait()

this.wait() returns a promise that will be resolved when this.continue() or this.throw() is called.

this.continue([value])

this.continue() resolves a the promise that this.wait() returns.

this.throw(err)

this.throw(err) rejects a the promise that this.wait() returns.

this.continue_cb(err, value)

this.continue_cb can be used to avoid boilerplate code like the following:

await task(async function() {
  fs.readFile('filename.txt', (err, value) => {
    if (err) {
      this.throw(err)
    } else {
      this.continue(value)
    }
  })
  let file_data = await this.wait()
  console.log('file data', file_data)
})

by replacing it with:

await task(async function() {
  fs.readFile('filename.txt', this.continue_cb)
  let file_data = await this.wait()
  console.log('file data', file_data)
})

task.sleep(ms)

A utility function that returns a promise that will resolve after ms milliseconds.

If you find any bugs or have a feature request, please open an issue on github!

The npm package download data comes from npm's download counts api and package details come from npms.io.