folktale / data.task

Migrating to https://github.com/origamitower/folktale
MIT License
425 stars 45 forks source link

Feature request: taskify #28

Closed reggi closed 8 years ago

reggi commented 8 years ago

Bluebird has a method called promisify and promisifyAll I'd really like to see taskify and taskifyAll methods, that convert node style callbacks to tasks.

var readFile = taskify(fs.readFile)

and

taskifyAll(fs)
var file = fs.readFileTask("./package.json", "utf8")
reggi commented 8 years ago

These functions seem super helpful

var _ = require("lodash")
var Promise = require("bluebird")
var Task = require("data.task")

var promiseToTask = function(promise){
  return function(){
    var args = _.values(arguments)
    return new Task(function (rej, res) {
      return promise.apply(null, args).then(res, rej)
    })
  }
}

var taskToPromise = function(task){
  return function(){
    var args = _.values(arguments)
    return new Promise(function (res, rej) {
      return task.apply(null, args).fork(rej, res)
    })
  }
}

var nodeStyleFnToTask = function(nodeStyleFn){
  return function(){
    var args = _.values(arguments)
    return new Task(function (res, rej) {
      args.push(function(err, result){
        if (err != null) {
          rej(err);
        } else {
          res(data);
        }
      })
      return nodeStyleFn.apply(null, args)
    })
  }
}
robotlolita commented 8 years ago

These functions are in the lift module from control.async: https://github.com/folktale/control.async/blob/master/lib/lift.js. Updated documentation for the control.async module is here: http://docs.folktalejs.org/en/latest/api/control/async/index.html :3

I'm particularly opposed to providing "taskifyAll" because it's just too much metaprogramming magic for me. I'd rather keep only the things that people can reason about statically.

You're free to write a library that provides "taskifyAll", of course :)

reggi commented 8 years ago

@robotlolita this is great thanks!