14 ms·
Bye Bye JavaScript Promises
- double051 12y agoThe 'code' blocks on this page are all using variable-width fonts, making it quite difficult to read the examples. Consider changing the 'font-family' to 'monospace'?
- vkjv 12y agoBluebird also solves 2 and 4: 2. Promise.prototype.bind 4. You can put try / catch / finally anywhere. It doesn't have to be in the end, but it does have to be close to what you want to wrap (just like any other try / catch). Coming form a large node project where I have been spending the better part of my waking hours for several weeks closing memory leaks caused by holding onto closures indefinitely, I would advise against the sort of meta programming advised in this article.
- api 12y agoJavaScript and C++ have a similar problem. There are so many ways to do so many things, that the result is endless stylistic fragmentation and tons of library bloat. C++ is getting better as C++11 introduces standard ways to do things like lambdas, tuples, etc., but JavaScript is obviously still in its experimentation phase.
- SerpentJoe 12y agoThere seem to be two major ideas going on here: CSP, and modifications to try/catch syntax. It would be easier to understand the former without the latter.
- aikah 12y agotldr; macros Yes but No.I personally think macros are the "root of all evil". Because they just make languages unreadable. That's one thing to have a complete different language that compiles down to JS,but as soon as you introduce macros is your code you make it harder to understand and document.I'm glad it works for you,but in my opinion the use of macros should be banned.While limited to nodejs, I personally think fibers are better alternative. 4. I actually think that it makes promises elegant. You can chain 20 then and have a single catch in case things are wrong,but you need to adjust the logic accordingly.Using different Error "classes" and checking the type is usually what I do. I still believe promises are an elegant way to deal with async programming,and ES6 lambdas will make them even less painfull. I'm not sold on generators for async programming strangely ,for multiple reasons(lack of support in browser land,especially on mobile). EDIT: macros are fine in LISP likes because it's not like these languages have a complex syntax. And in C,well you cant program without them. My point is javascript has enough features to make macros unnecessary.
- taeric 12y agoThis seems overly restrictive. Especially when, at a base level, macros should be easier to explain than some alternatives. It is quite literally, "take this and replace it with that." Don't get me wrong. They can hurt a codebase such that it is not readable anymore. But you know, functions can do similar. Heck, for some code basees, the same thing.
- aikah 12y agoI'd argue that sweetjs actually changes JS syntax,which is not the case with some other languages that have macros. If JS had Ruby's blocks, there would be no need for sweetjs. But I've heard TC39 wants to introduce macros in the future,so you might have them anyway...
- davexunit 12y agoRuby blocks are a poor substitute for a macro system. JavaScript already has something better than Ruby blocks anyhow: first-class functions.
- deleted 12y ago[deleted]
- pselbert 12y agoRuby certainly has first-class functions. Not only can you pass "functions" around as lambdas or procs, you can also detach and re-atach methods from a class or object at runtime. From the wikipedia: "Specifically, this means the language supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning them to variables or storing them in data structures" All of these things are certainly possible in ruby, see [0] fizzbuzz in the lambda calculus in ruby [0]: https://gist.github.com/tomstuart/1466504 https://gist.github.com/tomstuart/1466504
- lucian1900 12y ago
- doty 12y agoIt's interesting to me that people seem to be trying to bridge Promises with CSP. Why aren't more people investigating the more straightforward async/await transformation that the C# compiler does? CSP just seems like one transformation too far.
- Arnavion 12y agoasync/await is trivial to mimic with yield - run the outer-most generator in spawn, use yield* with "async" methods, and use yield with Promise-returning methods. Projects like Regenerator already know how to convert yield to straightforward JS. So you already have the transformation the C# compiler does.
- jkrems 12y agoasync/await is an upcoming JS feature that actually is kind-of supported by Bluebird when combined with generators. The author just didn't know about it (I guess) and reimplemented it via macros.
- mateuszf 12y agoIt works like this in ClojureScript.
- peterhunt 12y agoPromises + ES6 generators (Promise.coroutine() in bluebird) solve all of these problems.
- Arnavion 12y agoIndeed, I'm surprised the author doesn't know about them (or atleast doesn't mention them). Especially since even the async-await strawman (the first thing you'd find when googling for async-await in JS) demonstrates an implementation via generators...
- skeeterbug 12y agohttps://github.com/srikumarks/cspjs https://github.com/srikumarks/cspjs - The readme has benchmarks from bluebird generators. It is only 74 ms slower than the sweet.js solution. So the author knows.
- inglor 12y agoLook at the author's post on using promises. The author does not understand promises very well yet.
- moberemk 12y agoGenerators are up there with the let keyword in the list of "things I wish I had (native) access to already" because there's just so many use cases for them. This is definitely one combination I haven't thought of before though, so thanks for bringing it up!
- _greim_ 12y agoIs this similar to the co utility? I've been using it to yield partially-applied node calls directly, no promises required. var text = yield fs.readFile.bind(null, '/file.txt')
- inglor 12y agoYes, it's similar, `Promise.coroutine` is faster and a stronger abstraction though, especially with `addYieldHandler`.
- AgentME 12y agoIt seems like there's two ideas here: new error handling syntax, and new asynchronous task handling syntax. About asynchronous tasks: I think many people here might be interested in taskjs which combines Promises and ES6 generators (http://taskjs.org/ http://taskjs.org/) and the similar ES7 async function proposal (http://wiki.ecmascript.org/doku.php?id=strawman:async_functions http://wiki.ecmascript.org/doku.php?id=strawman:async_functi...). You can use await on a function that returns a promise and write code just like the code in this article (besides the error handling stuff). In basic sequential code, you never have to call .then() on a promise, but you're still able to dive down and do that if you have some non-linear asynchronous code that requires it.
- kin 12y agoA bit off topic but in the context of promises and Angular, I love the ability to set a set a promise for the timeout parameter. This is super valuable 'cause it lets me manually cancel any request instead of waiting for a response or timing out via time.
- aikah 12y ago> I love the ability to set a set a promise for the timeout parameter. please explain .
- Arnavion 12y agoI assume the grandparent is talking about functions in Angular that take in a numeric timeout parameter and wants them to take in Promises instead, so he can reject the promises to signal that he wants to cancel the operation. Kinda like CancellationToken in .Net, I guess.
- bengarvey 12y agoYou can pass a promise into an $http request as a parameter. If you hold on to this promise and resolve it before the request returns, it cancels the request. https://docs.angularjs.org/api/ng/service/$http https://docs.angularjs.org/api/ng/service/$http
- inglor 12y agoIf you'd like - we have a $q decorator in our code base that adds `.timeout` to promises and allows you to cancel them if the timeout expires (just like in Bluebird, from before we used Bluebird with Angular). Let me know if that's interesting to you and I'll put it on GH.
- andyzweb 12y agoI would be interested in seeing it posted~
- x86_64Ubuntu 12y agoI'm sure the JS world will just cook up 3 or 4 libraries to bolt on the desired functionality...
- moe 12y ago...each of which will have distinct bugs, leaks and gotchas. All of which will be incompatible and conflicting with one another.
- jerf 12y agoAnd thus does the javascript ontogeny finally finish recapitulating phylogeny, and we arrive at the inevitable end point: The Erlang/Go way is the best way to do this stuff after all. If you still end up using Javascript at the end of the process, hey, great, go nuts, but after years of swaggering optimism in the JS community about how somehow their stuff was so much better than anybody else's despite "event-based code" being extraordinarily well-trodden ground since the 1990s (as in being the default programming model for all serious code and entire major dominant operating systems), it might be worth people taking a moment to consider whether some more listening at the beginning of the process might have cut some years off this journey of discovery. The Javascript community has not been leading the charge of writing asynchronous code... they just caught up.
- Touche 12y agoWow, what a mean-spirited comment. You should seriously think about why you hate a community as bad as you obviously do.
- slowmovintarget 12y agoThat was not a mean-spirited comment, especially if you imagine someone with a bit more experience seeing the same thing recur needlessly. Grouchy with a touch of get-off-my-lawn, yes. Mean-spirited, no. Over-exuberance sometimes requires admonishment, especially when there is such a colossal waste of energy and effort like in the JavaScript "community" (OP's word, but still...). If JavaScript programmers spent more time listening and reading and less time posting "so I wrote my own" blogs we might have had things like Reactive libraries for JavaScript years ago. Throwing a word like "hate" around tells me you're likely too young to really understand what that means. Also, you picked on his tone and let the Go comment slide? Really? In short, get seasoned, dude.
- gagege 12y agoThank you, thank you, thank you. Even I, (young, unseasoned) know that criticism, admonishment and even a little "I told you so" do not equal hate. Ugh, that word.
- johnhenry 12y agoWhile reading this article, I remembered this: https://github.com/jlongster/js-csp https://github.com/jlongster/js-csp, which explicitly relies on es6 generators. I wonder if anyone can help us out by comparing and contrasting this to the subject of the article (https://github.com/srikumarks/cspjs https://github.com/srikumarks/cspjs).
- inglor 12y agoIT's very easy to criticise a technology when you're not using it correctly. Please consider reading the Bluebird usage examples, what you're doing is _definitely_ not the recommended usage. You can achieve what you're doing without any macros, with better throw safety, better debugging traces and more.