Re:Side Effects vs. Promises
by inglor on Sunday October 04, 2015 @01:36PM
(#10328135)
So much wrong in one place. A promise is the IO monad, with `then` being `>>=` [1].
If you write your promises code not to cause explicit side effects - it won't and you get pure code.
The fact you have (controlled!) side effects is the whole purpose of the IO monad. You can't avoid side effects or your program wouldn't do anything, a promise keeps the side effects in a box (the promise) and lets you code using boxes so that your code is purer. Of course, not all your code can be _actually_ pure because all code needs side effects.
The FUD about async/await is even stranger. JS _has_ async/await, it already shipped in Microsoft Edge (IE) and it's coming to other browsers. It is based on promises (just like it's based on Tasks = Promises) in C#.
The fact people talk so much about this without learning the topic is amazing. I'm genuinely disappointed with the quality of discussion in HN over these topics lately.
Monet is also a bad implementation of the IO monad in JS, in fact it's not an implementation at all. Here is an issue I opened there a while ago: https://github.com/cwmyers/monet.js/issues/25
[1] up to the fact `.then` does both `fmap` and `>>=` through overloading based on the return type. Seriously, if you remove the exceptions and the fact you can return an unwrapped value it's `Promise a -> a -> Promise b -> Promise b` for then's signature (the Promise a being `this`, the a -> Promise b` being the handler and the return value being itself).
Re:Side Effects vs. Promises
by inglor on Sunday October 04, 2015 @07:12PM
(#10329190)
The same way you'd write "code that doesn't cause side effects" in Haskell. You cause side effects. The thing is with promises (like IO) the side effects are limited to a box you can open, process and close.
So given the same input the same function will always return the same output. If you have a function that asynchronously computes a random number - it won't return different numbers and will always return a promise for a random number. It will never be observable that being called with a different input it produced a different output (as long as you don't mutate global state or anything like that).
In Haskell, IO is implemented in a way that causes side effects at the platform level. If there are no side effects there is nothing going on and the program is a no op after all :) Monads like IO are about _limiting_ side effects and _controlling_ state.
In Haskell, the lack of side effects is by the fact IO is provided by the platform. There is no fundamental difference between Haskell's `getLine` and the DOM's `fetch`, both return a boxed value.
Re:Side Effects vs. Promises
by dangoor on Sunday October 04, 2015 @09:00PM
(#10329471)
Thanks for the followup!
> In Haskell, the lack of side effects is by the fact IO is provided by the platform. There is no fundamental difference between Haskell's `getLine` and the DOM's `fetch`, both return a boxed value.
In his talk about "effects"[1], Chris Armstrong also talked about making testing easier in Haskell, though I paid less attention to that part, to be honest.
`fetch` returns a promise, but calling fetch causes the side effect to occur immediately. I don't know if that's how `getLine` works in Haskell. If I want to test code that calls `fetch` without an HTTP request actually hitting the network, I need to put in a mock `fetch`.[2]
Or, if there was another return type that put the side effect in a box that the platform handles later (or not at all, in the case of a test), that seems like a win.
[2]: another option, pointed out on Twitter, is that a promise (either from the fetch or from the test) could be passed in to the code under test. That seems less pleasant but requires no new machinery.
Re:Side Effects vs. Promises
by inglor on Monday October 05, 2015 @05:51AM
(#10330779)
Fetch doesn't actually make an HTTP call - that's the thing :) Fetch boxes a value so that the _platform_ can make an HTTP call.
You couldn't implement `fetch` yourself without platform APIs and you certainly couldn't do it in JavaScript without the DOM. The second suggestion you pointed (from Twitter) is exactly what you'd do in Haskell (you'd pass an IO from somewhere else). You can call it "pass an effect" if you'd like but it's the same thing :)
Re:Side Effects vs. Promises
by dangoor on Monday October 05, 2015 @10:03AM
(#10331850)
Indeed, the platform is responsible for the HTTP call, so I see what you mean. The side effect is happening in the platform itself. I should watch the second part of Chris Armstrong's video to see how he approached making testing nicer in Haskell.
Re:Side Effects vs. Promises
by danmaz74 on Sunday October 04, 2015 @07:17PM
(#10329203)
I read the OP's comment as: you can write the "then" functions as pure functions, and they won't have any side effects; those will then be isolated inside the code that resolves the promise - code that you usually don't write yourself as it is part of some library, as with "fetch(...)" for making an HTTP request.
Re:Side Effects vs. Promises
by dangoor on Sunday October 04, 2015 @09:02PM
(#10329477)
Sure, the `then`s could be pure functions but the whole point of my blog post is that I'd like to be able to test code that calls `fetch`. That would be possible if the actual side effecting operation is deferred to later, and not just the result.
Re:Side Effects vs. Promises
by asQuirreL on Sunday October 04, 2015 @02:18PM
(#10328282)
Not sure promises are equivalent to the IO monad in particular. They could form a Monad instance, although that is not the interface they have chosen to expose. It does seem it would be more similar to the `Either` monad, however.
Re:Side Effects vs. Promises
by inglor on Sunday October 04, 2015 @02:23PM
(#10328297)
The type signature, with `catch` is something like Either mixed with `IO`, it's just a specific form of continuation[1]. Promises are not _exactly_ like an IO monad because it would not be pragmatic, but it serves the same purpose (controlled side effects and boxing temporal state) in the same way (a bind operator).
If you look at all the examples online for `IO` [2] they all translate 1-1 to promises just fine :)
Re:Side Effects vs. Promises
by asQuirreL on Sunday October 04, 2015 @03:07PM
(#10328439)
Oh yeah, I totally agree, the examples for the IO monad match up very well to what can be done with Promises. My point was more that this is the case because the IO monad is the canonical black box monad: All you can do with it stems from its implementation of the monad interface, and so anything that behaves like a Monad will look very similar. This is tantamount to saying that Promises have a potentially useful Monad instance (which I am completely in agreement with you on).
The point about continuations is also a very interesting one, but I think again, stems from the same idea: Almost any monadic interface can be simulated with continuations.
Re:Side Effects vs. Promises
by saosebastiao on Sunday October 04, 2015 @12:31PM
(#10327957)
All of the back and forth on async callbacks vs async/await vs promises makes me sad that more people haven't yet discovered async computation expressions as found in F#. It is easily the most intuitive and expressive form of declarative async computation out there. I wish F# were more popular so it's revolutionary concepts like this one would bleed their way into other languages.
Re:Side Effects vs. Promises
by Chattered on Sunday October 04, 2015 @01:49PM
(#10328174)
I haven't used F# much, but aren't computation-expressions just a Haskell like do-notation, which you get for free because the async type constructors are a monad? Ocaml and Haskell should have this, at least, with lwt and its syntax extension, and Async respectively. I'm not sure what the situation is in Scala, but they surely have something similar with their generic for-comprehensions.
Re:Side Effects vs. Promises
by edgyswingset on Sunday October 04, 2015 @02:45PM
(#10328377)
I'm not a Haskeller and haven't played with monads knowing they were monads, but async in F# basically works like this:
1. Call the function with async { } block and have it return a computation object
2. Start that computation object in three primary ways:
a. On another thread, then wait (non-blocking) on it to finish
b. On another thread but don't wait for it to finish
c. On the current thread and don't wait for it to finish
There's a lot more details but that's going to cover probably 95% of the use cases.
My takeaways from it are:
a. Super easy to write code for it that's easy to read
b. Really hard to fuck it up
In my opinion, it's superior to the model that C#/VB have ... and pretty much every other language I've tried async support on. Have yet to use Haskell for it.
Re:Side Effects vs. Promises
by ufo on Sunday October 04, 2015 @03:00PM
(#10328420)
Async is like having do-notation, but without having to convert your code to do-notation! Do-notation is nice but having a single notation for everything is even better.
Both haskell and ocaml currently require you to use do-notation to write async code. I'm really looking forwards to algebraic effects landing in ocaml though because with that they will be introducing delimited one-shot continuations as part of the core language.
Re:Side Effects vs. Promises
by saosebastiao on Sunday October 04, 2015 @04:13PM
(#10328639)
It is very similar to do notation, but async expressions give you the ability to mix monadic and non-monadic code seamlessly and with uniform syntax within the same computation object. It's been a while since I've toyed with Haskell, but mixing regular Haskell and do-notation Haskell always felt like mixing two completely different languages.
Re:Side Effects vs. Promises
by msoad on Sunday October 04, 2015 @12:20PM
(#10327920)
I never liked the event oriented async programs. They are just harder to debug. Once you have more that a handful of evented object with couple of possible events you pretty much guaranteed to not know where to look for bugs.
Promises are not perfect either, but at least you can inspect them and thanks to new developer tools you can do it much easier.
Re:Side Effects vs. Promises
by munro on Sunday October 04, 2015 @05:18PM
(#10328869)
Bluebird makes debugging easy with long stack traces [1], and unhandled rejection detection [2]. Without the unhandled rejection detection, it's easy to get burned by forgetting to handle a rejection case, or use `.done()`.
Re:Side Effects vs. Promises
by inglor on Sunday October 04, 2015 @07:14PM
(#10329193)
As a bluebird contributor it's worth pointing out that while our stack traces are pretty sweet - unhandled rejection tracking exists in most modern promise libraries.
Re:Side Effects vs. Promises
by dclowd9901 on Sunday October 04, 2015 @12:39PM
(#10327980)
So what are we talking about here? Just wrapping side effects with a constructor so they're isolatable? You could just modify the Function prototype to mock a constant return for the same purpose, and it'd be completely transparent (no API littering the entire codebase).
Re:Side Effects vs. Promises
by greggman on Sunday October 04, 2015 @02:00PM
(#10328203)
Since we're talking about promises ... can anyone point to some good patterns for nested promises and not losing errors to the either?
Every time I use promises I find that I lose errors and it takes hours of adding console.logs all over the place until I find the place with the error some nested promise is hiding.
Re:Side Effects vs. Promises
by wildpeaks on Sunday October 04, 2015 @01:45PM
(#10328160)
I can't wait for async/await native in Node because they're imho required for really unlocking its potential; sticking only to es6 promises and generators feels incomplete.
Edit: I mean ES7 async, not async.js (even though it's a great library)
Re:Side Effects vs. Promises
by arianvanp on Sunday October 04, 2015 @01:17PM
(#10328084)
I've recently decided that all this async and evented stuff is just too hard to reason about. A proper language should have (lightweight) threads if it wants to support concurrency. Seems a lot easier to reason about.
Re:Side Effects vs. Promises
by inglor on Sunday October 04, 2015 @01:47PM
(#10328164)
You know, Haskell's IO is pretty much equivalent to JavaScript's promises. JavaScript's generators let you have do notation in JavaScript, and using async/await the "evented" stuff becomes not so evented and pretty easy to reason about.
I agree that it's not optimal, but the alternative (implicit IO) has its own share of pitfalls either. The async code that gets produced with modern JavaScript or Python is pretty easy to follow.
Re:Side Effects vs. Promises
by berryg on Sunday October 04, 2015 @04:01PM
(#10328607)
Take a look at elm-lang.org. It is a functional language that compiles to javascript. Effects are implemented as Tasks (as I understand kind of like a Monad). It has very good interoperability with javascript code.
Re:Side Effects vs. Promises
by krisdol on Sunday October 04, 2015 @12:55PM
(#10328027)
Personally, I hate promises, but on topic
> write unit tests for your code without mocking, by specifying the expected content, results, and order of side-effects performed by a function
No mocking? This is absurd. Some functions rightfully hit databases and the network. It either gets tested the right way, with mocks; the wrong way, with actual network calls; or not at all, as the author seems to suggest. Mocking belongs in some part in unit tests
Re:Side Effects vs. Promises
by bonobo3000 on Sunday October 04, 2015 @01:06PM
(#10328056)
If you can write very pure code, mocking is not needed. For example, a function for a database call could return a closure of what to do given a cursor into the database, or a SQL query which can be tested. The side-effecting functions themselves would just create a connection to a db or network host and do exactly what is prescribed in the request, making them simple enough to not need to unit test.
This is one of the big benefits of FP and pure functions really. I'm sure there would be practicalities that get in the way of doing this cleanly for all code, but it can go a surprisingly long way. The idea is to write a completely pure core and restrict input/output to be through a few small and obviously correct functions.
Re:Side Effects vs. Promises
by tel on Sunday October 04, 2015 @01:03PM
(#10328051)
The idea here is that you can separate your "functionality basis" which does require mocking because it genuinely hits the database from "composed functionality" which operates through a pure, monadic DSL and eventually calls down to the functionality basis.
In practice, that functionality basis can be far tinier than the set of things which would require mocking normally. This is a big win.
Also in practice you may want to make the functionality basis larger than it need be semantically because this can be a performance win.
Re:Side Effects vs. Promises
by ihsw on Sunday October 04, 2015 @11:56AM
(#10327843)
Promises in the JS world have lost out to async[1].
The callback pyramid madness has been traded for a simple and flat waterfall[2].
The constant .then and .catch when working with promises naturally makes a lot of people uncomfortable, and on top of that the async library provides a plethora of other collection manipulation and control flow utilities.
Frankly I think managing side effects should be abstracted away, and furthermore I cannot wait for C#-like async/await to become first-class citizens in the JS world.
Re:Side Effects vs. Promises
by aikah on Sunday October 04, 2015 @12:12PM
(#10327894)
> Promises in the JS world have lost out to async[1].
What (js) planet are you living on ? async package certainly has it's place, but the fact that promises are object you can pass around make them more useful than any async package.
> Frankly I think managing side effects should be abstracted away, and furthermore I cannot wait for C#-like async/await to become first-class citizens in the JS world.
Well too bad, because async/await will work with promises.
And I quote the blogpost :
> In practice, returning side effects rather than performing them and returning promises can increase the size of the “functional core” of your application, which is a win in my book.
Re:Side Effects vs. Promises
by notNow on Sunday October 04, 2015 @12:30PM
(#10327952)
Well too bad, because async/await will work with promises.
and promises are built on callbacks at the lower level.
I just don't really get these callback-intolerant people's averse reaction towards this construct when it's literally all over the place and those new abstractions are there to conceal them which is a good idea by the way but not to extinguish them completely as they might hope or believe.
Re:Side Effects vs. Promises
by aikah on Sunday October 04, 2015 @12:14PM
(#10327904)
> I have no data, but ES7 plans to support async/await, and Python 3.5 just shipped with it. I find it a strong signal already.
we're mixing up 2 different things here, the async package and the C# like async/await feature native to javascript. The async package while popular is certainly not more popular than promises.
Re:Side Effects vs. Promises
by phpnode on Sunday October 04, 2015 @01:50PM
(#10328179)
async/await is powered by promises, it's crazy to say that promises are going away, they're becoming an even more fundamental construct in the language.
If you write your promises code not to cause explicit side effects - it won't and you get pure code.
The fact you have (controlled!) side effects is the whole purpose of the IO monad. You can't avoid side effects or your program wouldn't do anything, a promise keeps the side effects in a box (the promise) and lets you code using boxes so that your code is purer. Of course, not all your code can be _actually_ pure because all code needs side effects.
The FUD about async/await is even stranger. JS _has_ async/await, it already shipped in Microsoft Edge (IE) and it's coming to other browsers. It is based on promises (just like it's based on Tasks = Promises) in C#.
The fact people talk so much about this without learning the topic is amazing. I'm genuinely disappointed with the quality of discussion in HN over these topics lately.
Monet is also a bad implementation of the IO monad in JS, in fact it's not an implementation at all. Here is an issue I opened there a while ago: https://github.com/cwmyers/monet.js/issues/25
[1] up to the fact `.then` does both `fmap` and `>>=` through overloading based on the return type. Seriously, if you remove the exceptions and the fact you can return an unwrapped value it's `Promise a -> a -> Promise b -> Promise b` for then's signature (the Promise a being `this`, the a -> Promise b` being the handler and the return value being itself).
The way I've seen promises used in JS is always in this pseudocode form:
- initiate something side effecty (making an HTTP request, for example)
- resolve the promise once the value is ready
Is there something you have in mind for how we'd write promises-based code without side effects in JS?
So given the same input the same function will always return the same output. If you have a function that asynchronously computes a random number - it won't return different numbers and will always return a promise for a random number. It will never be observable that being called with a different input it produced a different output (as long as you don't mutate global state or anything like that).
In Haskell, IO is implemented in a way that causes side effects at the platform level. If there are no side effects there is nothing going on and the program is a no op after all :) Monads like IO are about _limiting_ side effects and _controlling_ state.
In Haskell, the lack of side effects is by the fact IO is provided by the platform. There is no fundamental difference between Haskell's `getLine` and the DOM's `fetch`, both return a boxed value.
> In Haskell, the lack of side effects is by the fact IO is provided by the platform. There is no fundamental difference between Haskell's `getLine` and the DOM's `fetch`, both return a boxed value.
In his talk about "effects"[1], Chris Armstrong also talked about making testing easier in Haskell, though I paid less attention to that part, to be honest.
`fetch` returns a promise, but calling fetch causes the side effect to occur immediately. I don't know if that's how `getLine` works in Haskell. If I want to test code that calls `fetch` without an HTTP request actually hitting the network, I need to put in a mock `fetch`.[2]
Or, if there was another return type that put the side effect in a box that the platform handles later (or not at all, in the case of a test), that seems like a win.
[1]: https://www.youtube.com/watch?v=D37dc9EoFus
[2]: another option, pointed out on Twitter, is that a promise (either from the fetch or from the test) could be passed in to the code under test. That seems less pleasant but requires no new machinery.
You couldn't implement `fetch` yourself without platform APIs and you certainly couldn't do it in JavaScript without the DOM. The second suggestion you pointed (from Twitter) is exactly what you'd do in Haskell (you'd pass an IO from somewhere else). You can call it "pass an effect" if you'd like but it's the same thing :)
If you look at all the examples online for `IO` [2] they all translate 1-1 to promises just fine :)
[1] : http://blog.sigfpe.com/2008/12/mother-of-all-monads.html [2] : for example http://adit.io/posts/2013-04-17-functors,_applicatives,_and_...
The point about continuations is also a very interesting one, but I think again, stems from the same idea: Almost any monadic interface can be simulated with continuations.
But of course we're talking about IO... so my mental model is just that: mine and mine alone, really.
Outside of those, I don't know what the story is.
1. Call the function with async { } block and have it return a computation object
2. Start that computation object in three primary ways:
There's a lot more details but that's going to cover probably 95% of the use cases.My takeaways from it are:
a. Super easy to write code for it that's easy to read
b. Really hard to fuck it up
In my opinion, it's superior to the model that C#/VB have ... and pretty much every other language I've tried async support on. Have yet to use Haskell for it.
Both haskell and ocaml currently require you to use do-notation to write async code. I'm really looking forwards to algebraic effects landing in ocaml though because with that they will be introducing delimited one-shot continuations as part of the core language.
Promises are not perfect either, but at least you can inspect them and thanks to new developer tools you can do it much easier.
[1] https://github.com/petkaantonov/bluebird/blob/master/API.md#... [2] https://github.com/petkaantonov/bluebird/blob/master/API.md#...
Is there something like this for event systems?
I mean, if I send stuff to the server and wait for it to answer, promises work really well.
But what about things like onClick? The promise can only resolve once.
I've also personally been using Rx and RxJS a lot and have been enjoying it a lot over the past few years. Observables and async iterators are both features that are on standards track for the language. See https://github.com/zenparsing/es-observable and https://github.com/Reactive-Extensions/RxJS
Every time I use promises I find that I lose errors and it takes hours of adding console.logs all over the place until I find the place with the error some nested promise is hiding.
Here is a talk I gave about adding it last June: https://www.youtube.com/watch?v=LGpmUyFnyuQ
Personally, I recommend you use a faster richer userland library like Bluebird which has stronger unhandled rejection tracking.
Edit: I mean ES7 async, not async.js (even though it's a great library)
See go or haskell for example.
I agree that it's not optimal, but the alternative (implicit IO) has its own share of pitfalls either. The async code that gets produced with modern JavaScript or Python is pretty easy to follow.
Elm does look very nice. Not sure if I'd get the team on board with that kind of change ;)
[1]: https://www.youtube.com/watch?v=FV0DXNB94NE
> write unit tests for your code without mocking, by specifying the expected content, results, and order of side-effects performed by a function
No mocking? This is absurd. Some functions rightfully hit databases and the network. It either gets tested the right way, with mocks; the wrong way, with actual network calls; or not at all, as the author seems to suggest. Mocking belongs in some part in unit tests
This is one of the big benefits of FP and pure functions really. I'm sure there would be practicalities that get in the way of doing this cleanly for all code, but it can go a surprisingly long way. The idea is to write a completely pure core and restrict input/output to be through a few small and obviously correct functions.
Some people would insist that the closure is a mock, but otherwise this is correct, using closures in this way does help isolate one's tests.
In practice, that functionality basis can be far tinier than the set of things which would require mocking normally. This is a big win.
Also in practice you may want to make the functionality basis larger than it need be semantically because this can be a performance win.
The callback pyramid madness has been traded for a simple and flat waterfall[2].
The constant .then and .catch when working with promises naturally makes a lot of people uncomfortable, and on top of that the async library provides a plethora of other collection manipulation and control flow utilities.
Frankly I think managing side effects should be abstracted away, and furthermore I cannot wait for C#-like async/await to become first-class citizens in the JS world.
[1] https://www.npmjs.com/package/async
[2] https://www.npmjs.com/package/async#waterfall
What (js) planet are you living on ? async package certainly has it's place, but the fact that promises are object you can pass around make them more useful than any async package.
> Frankly I think managing side effects should be abstracted away, and furthermore I cannot wait for C#-like async/await to become first-class citizens in the JS world.
Well too bad, because async/await will work with promises.
And I quote the blogpost :
> In practice, returning side effects rather than performing them and returning promises can increase the size of the “functional core” of your application, which is a win in my book.
Which is exactly what I'm saying.
I just don't really get these callback-intolerant people's averse reaction towards this construct when it's literally all over the place and those new abstractions are there to conceal them which is a good idea by the way but not to extinguish them completely as they might hope or believe.
we're mixing up 2 different things here, the async package and the C# like async/await feature native to javascript. The async package while popular is certainly not more popular than promises.
Well cancel your signal because native browser APIs are returning promises:
https://developer.mozilla.org/en-US/docs/Web/API/MediaDevice...