9 ms·
Short ver: async await is now in an LTS release of node. Anything that returns a promise can now be run inline - ie, no endless .then() chaining - provided you'
by nailer 9y ago
Short ver: async await is now in an LTS release of node. Anything that returns a promise can now be run inline - ie, no endless .then() chaining - provided you've started an async context:
const writeFile = util.promisify(fs.writeFile),
request = util.promisify('superagent'),
stat = util.promisify(fs.stat),
sorts = require('sorts'),
log = console.log.bind(console)
const getJeansAndSaveThem = async function(){
var jeans = await request.get('https://example.com/api/v1/product/trousers').query({
label: 'Levi Strauss',
isInStock: true,
maxResults: 500
}).end()
jeans = jeans.sort(sorts.alphabetical)
await writeFile('jeans.json', jeans)
const status = await stat('jeans.json');
log(`I just got some data from an API and saved the results to a file. The file was born at ${status.birthtime}`)
}
Note: you should add error handling, I'm new to async/await and this code is to demonstrate a concept on HN, not to run your life support system. ;-)
- AngelloPozo 9y agoAsync await being part of core, not behind a flag, is probably my favorite new addition.
- Etzos 9y agoAsync/await support (without the --harmony flag) was made default in version 7.6 when they updated V8 to version 5.5. The biggest additions here with regard to async/await is the new promisify util and the async_hooks. Edit: Changed wording and included more detail.
- nailer 9y agoOf course, but most people don't run non-LTS node releases :-) Edit: originally wrote 'unstable'. Meant 'non-LTS'
- SparkyMcUnicorn 9y agoNode 7.6 is a stable release. Are you talking about LTS?
- Etzos 9y agoThe 7.6 release was no more unstable than the 8.0 release. Unless you're referring to the fact that 8.0 is going to be a LTS release. But if that's the case, it's not happening for a while yet, 6.10 is still the current LTS version.
- nailer 9y agoYou're right, corrected.
- deleted 9y ago[deleted]
- NoInkling 9y agoAnd some performance improvements. And the fact that there are more to come when they upgrade to V8 5.9 soonish.
- flavio81 9y agoAs noted, this already was possible in Node 7.x. But to use it, you needed a function that returned a promise. And many functions do not, due to having been developed earlier. This is true even for libraries done in 2016. Even today many Node.js developers don't seem to use async/await. At least in my country... And thus they live in braces {} hell. The improvement on the 8.0.0 version is that such an "oldie" function can be Promisified. A great improvement.
- simplify 9y agoBy "oldie" function, do you mean functions that expect node-style callbacks? e.g. function myCallback (err, result) {...}
- styfle 9y agoCorrect. Most node core APIs are written this way and now core ships an utility function[0] to wrap those functions in a promise. [0]: https://medium.com/@styfle/promises-in-node-js-8-x-core-d6a8a93e85a2 https://medium.com/@styfle/promises-in-node-js-8-x-core-d6a8...
- mastax 9y agoIt seems to me that Node should ship promisify-ed versions of all these functions (e.g. fs.readFileAsync). Over time they could replace the implementation with ones that use the OS Async APIs, though perhaps this step is unnecessary if you're already using an event loop underneath.
- lhnz 9y agoUntil then you can use `mz` for a modernised API[0]. [0] https://github.com/normalize/mz https://github.com/normalize/mz
- NoInkling 9y agoI mean, they've been debating about how to add a promisified API for years (see for example https://github.com/nodejs/node/pull/5020 https://github.com/nodejs/node/pull/5020) but nothing has come of it. util.promisify is a welcome addition, but very late for a first step.
- kasbah 9y ago>request = util.promisify('superagent') I don't think that's required. Superagent already returns promises.
- nailer 9y agoAh you're right! https://visionmedia.github.io/superagent/#promise-and-generator-support https://visionmedia.github.io/superagent/#promise-and-genera... Alas too late to edit comment.
- ujal 9y agoThere should also be something like awaitAll to replace await Promise.all calls.
- steve_adams_86 9y agoYou can make it yourself fairly easily I guess: const awaitAll = Promise.all.bind(Promise); async function foo() { var [val1, val2] = await awaitAll([func1, func1]); } It isn't ideal but it's a little cleaner
- nailer 9y ago+1. I'm a big fan of top level function binds to remove boilerplate and keep code readable: const log = console.log.bind(console), query = document.querySelector.bind(document), queryAll = document.querySelectorAll.bind(document);
- RReverser 9y agoYou don't need to bind `console.log` by the way (at least not in any recent version of Node.js or browsers).
- ujal 9y agoawait all([fn1, fn2]) ;) i wonder when we will get s-expressions for function calls (awaitAll [fn1, fn2])
- doublerebel 9y agoJust write (iced) coffeescript, s-exp are totally valid there: https://github.com/nextorigin/riemann-query-parser/blob/master/src/riemann-query.coffee https://github.com/nextorigin/riemann-query-parser/blob/mast...
- ujal 9y agoYeah, s-exps are the only thing I miss :(
- partycoder 9y ago1) This was possible in node 7 2) A request can fail and can timeout. 3) Writing to a file can fail. And you get the idea. Don't omit error handling. Error handling is business logic too. Being relaxed around error handling is the recipe for cascading server failure.
- nailer 9y agoI'm just getting started with async/await (like most people I stick to LTS releases) so please forgive the lack of error handling in the demo code!
- partycoder 9y agoAs someone who spends all day volunteering in Stack Overflow I hope people providing examples were a little bit better at emphasizing error handling. You should see the destructive effects of bad examples there.
- nailer 9y agoYou're welcome to add it.
- ryeguy 9y agoOh please. The point of the post was to illustrate the feature to those wondering "what's async/await?", error handling would be complete noise for that purpose.
- partycoder 9y agoI would argue with you, but I don't really have to prove you wrong. You will eventually prove yourself wrong, since deemphasizing error handling goes wrong very quickly.
- danneu 9y agoIn their snippet, errors would be handled altogether on the promise you get from `getJeansAndSaveThem()`. You don't have enough information to be outraged at the toy example.
- peterparada 9y agoYeah, most of the time, I need to handle errors with try/catch block.
- Rapzid 9y agoIs there a roadmap for supplying async/await interfaces for the entire stdlib? Still some event/callback based stuff in there that doesn't return promises or conform to the callback standard promisfy requires.
- mscdex 9y agoFWIW v8.0.0 is not an LTS release. Technically the first v8.x LTS release will happen in October. See this repo for more details: https://github.com/nodejs/lts https://github.com/nodejs/lts
- nailer 9y agoReplying to myself: since this comment is so popular, here's a fully working version for node 8: const util = require('util'), fs = require('fs'), writeFile = util.promisify(fs.writeFile), request = require('superagent'), stat = util.promisify(fs.stat), sorts = require('sorts'), log = console.log; const getPhotosAndSaveThem = async function(){ try { const response = await request.get('https://jsonplaceholder.typicode.com/photos'); const photos = response.body.sort(sorts.byKey('title')) await writeFile('photos.json', JSON.stringify(photos, null, 2)) const status = await stat('photos.json'); log(`I got some data from an API and saved the responses at ${status.birthtime}`) } catch (e) { log(`Oh no, something went wrong!`, e) } } getPhotosAndSaveThem()
- z3t4 9y agorant: why care about debugability and testability