r/webdev • u/tremendous_turtle • Aug 13 '17
Async/Await Will Make Your Code Simpler
https://blog.patricktriest.com/what-is-async-await-why-should-you-care/62
u/_wtf_am_I_doing Aug 13 '17
How the fuck are we on es7 already, I haven't even had time to look at es6
2
u/oculus42 Aug 13 '17
These are ES8. ES7 was just two changes. This is part of the 2017 spec, released at the end of June.
-2
1
0
Aug 13 '17
[deleted]
12
u/_wtf_am_I_doing Aug 13 '17
They keep coming out with all these changes but es6 Is still not fully supported in browsers.
4
3
u/mattaugamer expert Aug 13 '17
Honestly, though, this is a mistaken understanding of how all this works. A browser doesn't have to support every edge feature of one spec to implement useful bits of another. I wrote some code recently as a demo that fully used fetch and async/await. It will actually work on any evergreen browser, including Edge.
You should be treating these things individual functionality items, not expecting 100% support before using it.
1
u/vinnl Aug 14 '17
If they wait with "coming out" with those changes only after browsers supported all earlier changes, that would just mean that they would release the same changes they do now, only later in time...
0
Aug 13 '17
[deleted]
11
u/OriginalName404 Aug 13 '17 edited Aug 13 '17
Maybe it's just me, but last week I tried using Babel to transpile async/await to ES5 and it totally broke breakpoints in the Chrome debug tools, making the code nigh on undebuggable.
I'll take messy promise-based code over cleaner but impossible-to-debug async/await code any day.
Edit: Not that this is any reason not to use it in NodeJS applications, like the article suggests. It's a lovely way to program, but I fear it's just not ready for use in browsers yet.
17
u/CommandLionInterface Aug 13 '17
Browser breakpoints require you to output sourcemaps, make sure they're being put out and being loaded. I've had trouble with babel and webpack and sourcemaps before.
4
u/OriginalName404 Aug 13 '17
Yeah, I think it's to do with how async/await are transpiled to es6 generators and then to promises. Guessing it's inaccurate source maps given the complexity of the input vs output code.
For the record, source maps and breakpoints worked fine compiling async/await to es6, just not to es5.
1
u/highmastdon Aug 14 '17
But even when using source maps, the console, which usually let you execute statements in the code at the current debugger point, is completely broken. Especially when you use source maps created by web pack which has a babel loader. Then you can inspect a variable using source maps, but NOT on the console, you'd have to refer to the original variable name as it was compiled by webpack. E.g. _ (from lodash) becomes
__lodash1__2
u/NoInkling Aug 14 '17
Chrome supports async/await natively now, and has improved async debugging capability... is there any reason you can't debug using native code and only transpile for production?
0
Aug 13 '17
Wrap it in try/catch
0
Aug 14 '17
[deleted]
1
Aug 14 '17
Whats a better way?
0
Aug 14 '17
[deleted]
1
Aug 14 '17
most async things on the client are xhr requests. I log those failures so that its easier to debug. also idk how to handle errors using async/await without try/catch.
0
u/_wtf_am_I_doing Aug 13 '17
Yeah I was looking at that recently, think I will probably start working with it.
0
Aug 13 '17
[deleted]
1
u/_wtf_am_I_doing Aug 13 '17
Lol what do you mean
0
Aug 13 '17
[deleted]
3
u/GreatDant0n Aug 13 '17
TL;DR: it's a horrible mess
I wonder if you are able to login to Reddit without password manager :D
3
u/re1jo Aug 13 '17 edited Aug 13 '17
And this is why I'm still whipping up Bootstrap 3 layouts and using mostly Vanilla JS with bits of jQuery thrown in (couple of it's selector functions still come in handy).
I'm up to date with many techs, but I keep going back to what I can use deploy fast.
1
u/pomlife Aug 13 '17
Hopefully you're using jQuery for static sites and not full-fledged applications. If so, I assume your testing is a nightmare and anything you write to make changes to the DOM becomes more and more difficult as your state becomes more complex.
→ More replies (0)0
1
1
0
Aug 13 '17
[deleted]
8
u/oculus42 Aug 13 '17
JavaScript was originally proprietary to Netscape, and was turned into a public language called ECMAScript, though most people still call it JavaScript. Recently, they have decided to come out with yearly updates to the language, and use year names, but the specifications are still versioned, causing some of the confusion.
These versions are released at the end of June.
ES6 = ES2015, which is the first major update in a decade. Most of the "new things" in JavaScript are ES6.
ES7 = ES2016, which was only two small additions.
ES8 = ES2017, which includesasync/await.Current browsers have pretty broad support for ES6, but there are some small gaps that you may need to watch for if you are pushing the limits.
You can check out support for specific functionality in the Browser Compatibility section of most MDN pages. or look at caniuse.com for the feature.
Edit: formatting.
2
u/pomlife Aug 13 '17
Actually, going forward, only ES + year will be used.
1
u/oculus42 Aug 14 '17
The year is the name, but the edition numbers continue to exist, too.
ECMAScript® 2017 Language Specification 8th edition (June 2017)And the actual title of the current spec is:
ECMAScript® 2017 Language Specification (ECMA-262, 8th edition, June 2017)
So we call it ES2017, but it is still ES8, too. Even the URL is "8.0": ecma-262/8.0/index.html.
1
0
u/NoInkling Aug 14 '17
I mean, they've been saying that for a while, but in practical use it hasn't really happened. Even the spec for ES2017 calls itself the "8th edition" to help with the confusion.
3
u/way2lazy2care Aug 13 '17
JavaScript was originally proprietary to Netscape, and was turned into a public language called ECMAScript, though most people still call it JavaScript.
You're not totally accurate. ECMAScript and JavaScript are separate. There are multiple ECMAScript languages of which JavaScript is one. Features outlined in ECMAScript are just a subset of features of JavaScript.
1
u/_wtf_am_I_doing Aug 13 '17
They are different, newer versions of JavaScript.
0
Aug 13 '17
[deleted]
3
u/_wtf_am_I_doing Aug 13 '17
You don't have to declare a JavaScript version. Unfortunately the newer versions aren't supported in browsers so you can't really use them without a precompiler like Babel. Babel will compile es6 down to browser supported code that runs in all browsers
4
u/mattaugamer expert Aug 13 '17
It's worth pointing out that huge amounts of these features are now fully supported by browsers assuming you can ditch IE support.
0
Aug 13 '17
[deleted]
4
u/_wtf_am_I_doing Aug 13 '17
Honestly I would go with react. I have never uses angularjs 1 but have done alot with angular 2. Angular 2 is a ton of stuff to take in and the documentation has no clear place to start so it is super hard to get into. React is very fast and lightweight and easier to learn. Google made angular so if you aren't trusting a framework made by Facebook then your probably won't want to use angular, even though I'm not sure what you're worried about
0
Aug 13 '17
[deleted]
1
u/_wtf_am_I_doing Aug 13 '17
It was just alot to take in for me at the time(typescript, es6, and being my first framework) maybe not how it is for everyone.
1
u/anObscurity Aug 14 '17
It was the same for me. I was very proficient in Angular 1.x, but reading through Angular 2+ documentation was a nightmare. Switched to React, haven't looked back.
→ More replies (0)0
Aug 13 '17
[deleted]
8
u/OmegaVesko full-stack Aug 13 '17 edited Aug 14 '17
Dude, React isn't going to collect or sell your data. There are reasons one might not want to use React over other frameworks, but that's sure as hell not one of them.
1
u/_wtf_am_I_doing Aug 13 '17
Yeah they do a ton of the data selling and stuff like that but I'm pretty sure they don't have that in the framework. You can actually just go through the code and see what it is doing if you wanted. I would just google some tutorials for it like from tutorials point or from their official site. Also i would recommend using jsx templating instead of the other option (can't remember what it is right now)
2
u/-Piper- Aug 13 '17 edited Aug 23 '25
zephyr deliver middle offer punch childlike rhythm vegetable light piquant
This post was mass deleted and anonymized with Redact
0
Aug 13 '17
[deleted]
1
u/-Piper- Aug 13 '17 edited Aug 23 '25
aback heavy carpenter cable rock books aware roll continue rain
This post was mass deleted and anonymized with Redact
1
u/muffsponge Aug 14 '17
I've been using async/await with typescript for a while now. I absolutely love it, except for one drawback, the transpiled/compiled code is a nightmare to debug. Can't wait for it to be widely natively usable.
1
-14
0
Aug 13 '17
[deleted]
3
u/pomlife Aug 13 '17
You were writing .catch anyway, weren't you? It's the same thing sans another indentation level.
1
1
u/tech-ninja Aug 25 '17
But sometimes you don't want to simply catch everything right?
With promises you had the distinction... you could do
promise.then(onFulfillment, onRejection);which is not the same as
promise.then(onFulfillment).catch(onAnyError);The second one will catch everything and will make some errors hard to debug and the first one only catches gracefully rejected promises.
0
Aug 14 '17
[deleted]
0
u/pomlife Aug 14 '17 edited Aug 14 '17
(async () => { try { const firstValue = await getFirstValue(); const secondValue = await getSecondValue(); const thirdValue = await getThirdValue(); console.log(`Got ${firstValue}, ${secondValue} and ${thirdValue}.`); } catch (e) { console.error(e); } })(); // vs. (() => { getFirstValue() .then(firstValue => { getSecondValue() .then(secondValue => { getThirdValue() .then(thirdValue => console.log(`Got ${firstValue}, ${secondValue} and ${thirdValue}.`)); }); }) .catch(e => console.error(e)); })();1
u/OmgImAlexis Aug 14 '17
Why not something like this?
(() => { const first = await getFirstValue(); const second = await getSecondValue(); const third = await getThirdValue(); Promise.all([first, second, third]) .then(([firstValue, secondValue, thirdValue]) => console.log(`Got ${firstValue}, ${secondValue} and ${thirdValue}.`))); .catch(e => console.error(e)); })();6
u/pomlife Aug 14 '17
a) The first line has no async, so you get an error.
b) Awaiting them all means first, second and third have values, so the Promise.all is not necessary, since you already have the values. The simplified version is my first example.
1
u/PM_ME__YOUR__FEARS Aug 14 '17
(function(){ Promise.all([ getFirstValue, getSecondValue, getThirdValue ]) .then(([firstValue, secondValue, thirdValue]) => console.log(`Got ${firstValue}, ${secondValue} and ${thirdValue}.`))); .catch(e => console.error(e)); })();1
u/pomlife Aug 14 '17
That's not doing the same thing as my first example, since it's firing all three asynchronously instead of one after the other.
1
u/PM_ME__YOUR__FEARS Aug 14 '17
Ah I see, good point.
They don't explicitly rely on each other so I didn't notice that was a requirement.
1
u/bluebaron Aug 14 '17
These could be rewritten to not look so verbose and nested. For your second example:
(() => { function seqPromises(...promises) { return promises.reduce( (acc, p) => acc.then(acc_ => p.then(p_ => acc_.concat([p]))), Promise.resolve([])) } seqPromises(getFirstValue(), getSecondValue(), getThirdValue()) .then([first, second, third] => console.log(`Got ${first}, ${second}, and ${third}.`)) .catch(e => console.error(e)) })()For your third example, assignment to those variables doesn't really achieve anything, and could be written as
(() => { Promise.all(getFirstValue(), getSecondValue(), getThirdValue()) .then([first, second, third] => console.log(`Got ${first}, ${second}, and ${third}.`)) })7
u/pomlife Aug 14 '17
Do you really think your first example is cleaner than my first example?
1
u/bluebaron Aug 14 '17
I didn't say that at all, but your examples were a misrepresentation of the verbosity/nesting necessary to use promises effectively.
async/awaitare really just syntactic sugar for those more used to imperative programming. Personally, I don't find that they clarify the code much at all, because I prefer functional style. Additionally, when one works with the Promise objects themselves, composition is facilitated, which I value highly.I'm not sure if you intended/knew this, but your examples aren't all semantically identical either--while the first two perform asynchronous work sequentially, the last one does so concurrently, which could matter if you were working with stateful requests or something like that.
0
Aug 13 '17
[deleted]
10
u/cyphern Aug 13 '17
Synchronous fetch will cause the thread to block. None of your other javascript will be able to execute until the fetch is complete. For example, if there's an onClick handler on some element and the user clicks it, that onClick handler will not be executed until the fetch is completed.
Async / await is basically using promises under the hood. When you start the fetch, your function will yield the thread, thus allowing other code to execute. When the fetch is complete, the event loop will resume executing where it left off.
0
Aug 13 '17
[deleted]
-4
u/haikubot-1911 Aug 13 '17
I thought this was not
Possible with fetch. Do you
Have an example?
- tiko844
I'm a bot made by /u/Eight1911. I detect haiku.
2
u/NoInkling Aug 14 '17
It's already been explained, but this is how I think of it:
In order to use await you need an async function context.
awaitwill pause the function itself, but since an async function always (immediately) returns a promise when it's invoked, the calling code will continue executing (unless that promise is also awaited, in which case the process repeats up the chain until you get to a non-awaited invocation). This is why it's non-blocking.
0
Aug 14 '17
[deleted]
1
u/tremendous_turtle Aug 15 '17
Yes, you could use the ".then()" syntax to access the value, but you can also just use the async/await syntax, like so -
window.addEventListener('DOMContentLoaded', async () => { let res = await asyncHelloWorld() console.log(res) }); async function asyncHelloWorld() { let string = 'Hello World'; return string; }1
u/senocular Aug 14 '17
Yes, to get to the string 'Hello World' after calling asyncHelloWorld, you would use then(), or await it in another async function.
0
Aug 14 '17
[deleted]
1
u/OleWedel Aug 14 '17
awaitis used withasync. An exampleasync () => { const res = await myPromise(); console.log(res) }
yieldis used with generators. An example (not that there are no fat arrow generator functions yet)function * () { const res = yield myPromise(); console.log(res); }There are some difference that might be good to know but if all you are doing is waiting for something async I don't think you will notice a different. I am pretty sure Babel compiles
async/awaitinto generators andyield.1
u/senocular Aug 14 '17
await is also inherently asynchronous - as it works with promises - while yield is not. async/await can be, in many ways, seen as the async version of function*/yield.
42
u/zeerorg Aug 13 '17
It's the best thing that's happened to NodeJS. Promises are good but don't do much in simplyfing it for developer. You still need to write a lot of call backs (then and catch). async awit add a good workflow and you can always fallback to promises when you need them.