Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the Difference Between Javascript "Promises" and functional Programming's "Task"?

Besides lazy execution, are Tasks and Promises pretty much the same thing? When I refer to a task, I refer to a class that is in its most basic behavior like the following:

class Task {
  constructor(then) {
    this.then = then;
  }
  map(mapper) {
    return new Task((resolve, reject) => this.then(
      x => resolve(mapper(x)),
      reject
    ))
  }
  flatMap(mapper) {
    return new Task((resolve, reject) => this.then(
      x => mapper(x).then(resolve, reject),
      reject
    ))
  }
}

What type of (class?) is a task/promise? I'm learning about functional programming approaches, but I don't think I've gotten to this type yet. Is it a type of monad?

like image 825
MFave Avatar asked Feb 18 '26 21:02

MFave


1 Answers

Yes, the key thing is a monadic bind, or a flatMap in your case that has the signature:

Task A -> A -> Task B -> Task B

With promises - that's the then method that:

Promise A -> (A -> Promise B) -> Promise B
 this          onFulfilled        return value

In fact, both are instances of the Continuation Monad. Lots of other things (like Rx streams) are instances of the continuation monad.

Promises in JavaScript however are specced with a slightly different (and uglier, for arguably practical reasons) signature with it being possible to also return a plain value from then, and there are exception semantics involved.

There was a push for more "monadic" promises back in 2013 when they were specced, but it failed. The current promises in JavaScript aren't really "monad"s per-se.

like image 61
Benjamin Gruenbaum Avatar answered Feb 20 '26 10:02

Benjamin Gruenbaum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!