origamitower / folktale

[not actively maintained!] A standard library for functional programming in JavaScript
https://folktale.origamitower.com/
MIT License
2.05k stars 102 forks source link

Implement Task.do() to integrate Tasks with JS syntax #111

Closed robotlolita closed 7 years ago

robotlolita commented 7 years ago

Folktale should add a Task.do(generator) function that allows using generators to integrate Task with JavaScript's syntax, like async/await does for promises. In essence, this would allow one to write:

const readFile = task((resolver) => ...);

const someTask = Task.do(function *() {
  const fileA = yield readFile('a.txt');
  const others = yield Task.parallel([readFile('b.txt'), readFile('c.txt')])
                           .map(xs => xs.join(''));
  return fileA + others;
});

someTask.run().listen({
  onCancelled: () => ...,
  onRejected: (reason) => ...,
  onResolved: (data) => console.log(data)
});

Why?

Since people can convert a Task's execution to a promise, they're already able to use async/await, but that requires buying into the disadvantages promises have. In particular, the fact that promises catch errors automatically, and recursively tries to assimilate any object with a .then method may make programs harder to reason about.

Task.do would provide similar syntactical sugar as async/await does, without the semantic drawbacks of promises.