origamitower / folktale

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

Would like help in documenting Future #200

Closed Fl4m3Ph03n1x closed 6 years ago

Fl4m3Ph03n1x commented 6 years ago

Background

I am reading every inch of the docs and trying to learn about Folktale as much as I can. Recently, I decide to try Future.

Do we need a Future?

Now while I understand the difference between Task and Promise and between Task and Future ( support for cancellation ) it is not clear to me the difference between Future and Promise.

Why would I ever want to use a Future instead of a Promise ? What benefits would I have? Well, you can say: "This way you actually have a monad, instead of a sorry excuse for a monad".

And that is a fine argument on it's own but... having in mind I always need to convert from Promise to something else ( to future ) and that the Future's API is pretty much the same, it is not clear to me, as someone new, why I should care about Future at all.

Code sample

Lets assume I have this function, where request is a function that makes a request and returns some results.

extractRequestInfo is a function that extracts data from the response object. If something fails, I catch the error and return an object with all the data, the badId and the error.

const requestFruit = request => data =>
    request( data )
        .then( extractRequestInfo )
        .catch( error => ( { badId: prop( [ "Id" ], data ), error } ) );

Given that this is an HTTP request, I know I don't need a Task because there is no cancellation I can do here. So my options are Promise and Future.

Questions

  1. How would I use Future in this sample?
  2. Since this is something that can fail, should I use Result as well?
robotlolita commented 6 years ago

Future solves the same problem Promise does, so there isn't much of a conceptual difference between the two. The difference is more in how they solve the problem.

Promises can either settle successfully or fail. In any transformation you apply to a promise's value, errors thrown synchronously will be implicitly caught and reject the promise as well. This is interesting in async/await because you can handle these errors (synchronous and asynchronous) in a similar way--you don't need to lift every synchronous operation into a promise, because the runtime will do that for you.

The downside of this is that it's very easy to catch errors that you didn't intend to, and have your system run in an inconsistent state. I don't think you can do much with static analysis here either.

Futures don't have that problem because nothing is lifted into a future implicitly. If you want synchronous operations to use the Future pipeline for handling errors, you have to put them there explicitly. This gives you more control over error handling, and uncaught errors will still crash the process as expected (avoiding having your program run into inconsistent memory states for cases you didn't predict), but it takes more effort to write programs this way.

Other than that, if you consider Tasks, Futures model the eventual value of a Task with a success case, a failure case, and a cancellation case. Promises only have a success case and a failure case, so cancellation is modelled as a special failure value. This changes the idioms for handling cancellations a bit. It's possible for code using promises to handle failures without being aware of this special cancellation value, which may be a problem since this value may easily be lost during these transformations.

In codebases that mix promises and tasks, these problems are more complicated because the implicit-lifting of errors that promises do is not very compatible with the explicit-lifiting of errors that tasks/futures expect (this can lead to problems like this one: https://github.com/origamitower/folktale/issues/163). Finding these bugs becomes a lot harder than if you had only promises or only tasks/futures. Not sure what's the best way to handle these cases yet.


Anyway, about your questions:

1) How would I use Future in this sample?

You can't construct a Future directly, so you'd have to do it through a Task anyway:

const requestT = task.fromPromised(request);
const requestFruit = data =>
  requestT(data).map(extractRequestInfo).orElse(error => ({ badId: prop(['Id', data), error }));

const fruit = requestT("apple").future();

So you use Task for operations you can run more than once, and future (or promises) for representing eventual values from a particular execution, on which you may want to depend on, but without causing new HTTP requests to be made in this case.

You can think of it as a form of memoisation/caching.

2) Since this is something that can fail, should I use Result as well?

Futures, Tasks, and Promises all have their own notion of failure, so you probably want to use that unless you want to handle different kinds of failure differently.

For example, if you're representing an HTTP request, you might want to handle the completion of the request (i.e.: you hit the server, and it returned a response), from the semantics of the response, which may indicate an error (e.g.: the server returned a 404 response). In that case you'd probably have something like Promise/Task/Future<Result<Body, ErrorResponse>, ConnectionError>

robotlolita commented 6 years ago

(the docs will probably move to MkDocs + ESDoc soon to make them easier to read btw. Besides the missing documentation in some objects, the structure of the documentation right now is not easy to follow :/)

Fl4m3Ph03n1x commented 6 years ago

Thanks for the reply!

So, I was thinking that Future was actually the same as Fluture but now I see this is not the case ( instead, it should be a task ).

The one thing I still don't get, is that if Tasks are basically better Promises ( lazy execution, FL compliant, allow for cancellation ) then why do we need a Future in the first place?

Is there any scenario where you would use a Future without using a Task? ( I take it is not even possible, right ?)

robotlolita commented 6 years ago

I'd say it's more that Futures are supposed to be "simpler Promises" (in the sense that each method in the Future API does less work than the equivalent method in the Promise API).

Tasks don't really have an equivalent type in JavaScript. If anything it's closer to C#'s Task type, but without the parallel execution part, and we don't support cancellation tokens (cancellation capabilities are provided by the TaskExecution object instead).

You can create synchronous Future without using a Task, which is useful when you're doing transformations on values in futures. You could also create a Future in an asynchronous operation using the low-level Deferred object, but that's an internal API because it's easy to make mistakes that lead to race conditions that are harder to debug--Task avoids some of that problem.

Fl4m3Ph03n1x commented 6 years ago

I think I got it all now! Thanks for the help!