11 ms·
Microsoft Edge gets native ECMAScript 7 async/await support in latest build
- nailer 11y agoFor anyone unfamiliar with JS, async/await is about the best JavaScript will ever get: var orders = await getJSON('/users/joe/orders'); No callbacks, promises etc (Edit: that you have to look at, as other posters note the implementation uses promises in the background). You still have to explicitly say you want to be async, so it's not quite as good as non-blocking IO in something like Elixir, but it's the future as far as JS goes.
- xlm1717 11y agoI'm not sure about the no promises and no callbacks part. The similar line they use in their examples doesn't define a separate getJsonAsync function in the "Asynchronous city" section (and, as far as I can tell, there's no native getJSON function). That, and the fact that the line immediately preceding the await call has a comment that says, "just have to await the promise!", leads me to have to assume they used the function defined in the promises section, which of course uses promises. And, in order to define that promise, they do have to use three callbacks. With functions and just callbacks I can make one-liners for fetching data too if I abstract away all the stuff that actually does the fetching of the data: getJSON('/users/joe/orders', function(orders) {} );
- nvivo 11y agoThe parent exaggerated a little. async/await does use promises. In fact, it's built around them. All async functions return promises, and all await expressions await on promises. Currently on babel implementation with facebooks's regenarator it seems to work on any "thenable", because I got it working with jquery and angular promises.
- callahad 11y agoDepending on which transforms you enable, you can also eliminate Regenerator and use native ES6 promises and generators. E.g: https://gist.github.com/callahad/b99c83d6d9fd675137b7 https://gist.github.com/callahad/b99c83d6d9fd675137b7 Promises are sufficiently supported in the latest versions of all major browsers, and Generators are almost there. They're supported in Firefox and Chrome, behind a flag in Edge, but unsupported in Safari. But if you're targeting Node 4.0, you might as well transpile down to ES6 instead of going all the way to ES5 and pulling in Regenerator :)
- callahad 11y ago> as far as I can tell, there's no native getJSON function There is a standard, native fetch() function which is pretty darn similar: https://hacks.mozilla.org/2015/03/this-api-is-so-fetching/ https://hacks.mozilla.org/2015/03/this-api-is-so-fetching/
- jlongster 11y agoThere are promises there, it just hides it. All async functions return a promise, and `await` works with promises builtin. It's basically the same thing as generators, without the `function*` syntax. Which is unfortunate because async/await only works with promises, and if you want any other async model (like one that doesn't eat errors all the time) you can't use it. Luckily, generators are fine.
- nailer 11y agoThat's correct, I've edited my post to be clearer. Thanks.
- SerpentJoe 11y agoI'm confused, I don't know what type of errors a promise eats. If you're chaining together promises returned by other routines, especially with async/await, then error propagation and handling is very natural. If you're creating a promise using `new Promise` then you can use reject to propagate errors. How does this fall short of other async models?
- grayrest 11y agoThe problem isn't the propagation, it's the propagation by default. He wants errors that occur in development to pop a stack trace as soon as the error occurs without needing to attach a .catch handler.
- spb 11y agoBut... it's an async call. The error is going to happen as part of the event loop. That's inherent to the nature of async. If you want to get the error before it happens, you'll need a time machine.
- colin_jack 11y agoIts not about getting errors before they happen: http://jlongster.com/Stop-Trying-to-Catch-Me http://jlongster.com/Stop-Trying-to-Catch-Me
- Kiro 11y agoWhat's so good about it? I still want to fire some kind of callback when it's done. Or am I missing something?
- smcl 11y agoI can't see either - would be nice to see\understand a little more what's so special about it.
- mateuszf 11y agoWhen it's done, you will have the value in orders variable. If you can do something with it - just do it in new line in the same scope. You can also use catch exceptions using standard try catch block.
- Loque 11y agoIt's just sugar, and allows people to write JS do to this in a more consistent manner.
- nailer 11y agoYou only want to fire a callback because that's how you did async previously. In reality, all you want is async.
- mschuster91 11y agoFinally, a way out of callback hell. Now, make this work with IndexedDB and I might revisit IDB.
- streptomycin 11y agoHere's some work towards that: https://github.com/inexorabletash/indexeddb-promises https://github.com/inexorabletash/indexeddb-promises Still a ways to go, though...
- dang 11y agoAlso https://news.ycombinator.com/item?id=10310932 https://news.ycombinator.com/item?id=10310932.
- msoad 11y agoI'm surprised to see Microsoft put a higher priority for async/await than finalized ES2015 spec. Some of ES6 stuff are still missing in Edge. As a side note, I don't like how async/await has to be wrapped in try/catch AND a function for proper error handling (async ()=> try { let result = await fetch('/file.json'); let json = await result.json(); console.log(json): } catch(error) { console.error('Not sure fetch failed or toJson'); } )(); if you want to handle each error separately you need even more try catch!
- nvivo 11y agoTo be fair, all browsers are still missing ES6 features and all of them have newer stuff being implemented. As for the try catch, you don't NEED to wrap. The sample just shows you can. You can't do: try { promise.then(() => ...); } catch {} but you can do try { await promise; ... } catch {} async/await is a way to write simpler code the same way you would use a "for" block instead of a "while(iterator.next())" - because it's easier, all the rest is still the same.
- msoad 11y agoYou need to wrap in try/catch if you want to handle the errors, which is the same for sync functions that throw to be fair. But most of async operations are somehow expected to fail due to their nature (like network calls) and people usually want to have error handling scenarios. But for sync functions we usually let the error terminate the program because if a sync function throws in runtime it means something is wrong in my program, not in networking...
- nvivo 11y ago> You need to wrap in try/catch if you want to handle the errors. Of course, the same way you need to add a second callback to a promise handler if you want to handle errors. There is no difference, really. You're just changing the way you write the code. Also, you're not forced to choose "await or promises". You can use both as you see fit, in the same block: async () => { // make 2 requests in parallel var p1 = fetchSomething(); var p2 = fetchAnotherThing(); // wait for both of them to be done await Promise.all(p1, p2); // continue when they're both resolved // these "await" only get the values since the promises are resolved doSomethingWithTheValues(await p1, await p2); } > But for sync functions we usually let the error terminate the program because if a sync function throws in runtime it means something is wrong in my program, not in networking This is just the way you're choosing to see the problem. Promises can be used for anything, it's not tied to networking. I usually write promises that will be resolved when a modal window closes or when an application event happens. It's just a simpler way to write code. The way you use it is up to you. Also, async/await makes debugging a lot easier. The debugger can understand that the next expression after an "await" is supposed to be in the same function context. No more adding breakpoints to the callback function because only you know how the code is called at runtime. You debug async functions as normal functions.
- callahad 11y agoIf you'd like to follow along on the Firefox side, CC yourself on https://bugzil.la/1185106 https://bugzil.la/1185106
- daveidol 11y agoThe first time I heard of async/await was actually with Microsoft C#; so I'm not too surprised to see them prioritize this feature in JS land. ...which is cool, because using async/await in C# made me realize how much simpler dealing with async code could be (compared to my experience with JS callbacks or Java threads).
- apaprocki 11y agoIt was the first interaction we (at Bloomberg) had with async/await as well. We really wanted to see it come to JS and as the spec was evolving it was clear that the path to getting there (if TC-39 ultimately agreed async/await was a desired thing) was going to be via generators. That is how we wound up getting involved with Igalia back in Feb 2013. I kicked off a multi-year project with Andy Wingo / Igalia to direct his mighty keyboard at generators and get them landed in v8. We weren't quite sure TC-39 would agree async/await was a good thing in the end, but it seems now all the pieces are finally coming together. It is satisfying to see the endgame within reach right now and I hope it is worth it once it starts to become more widely available! Companies -- help get spec features implemented! We essentially acted as the bank when it came to the generators work. You don't need to land the code yourself to help move the needle. Thank you Igalia for being awesome.
- stupidcar 11y agoI know you guys at Bloomberg have also sponsored Igalia to work on implementing CSS Grid Layout as well. Most web devs seem to be unaware, but I assure you those of us who are definitely appreciate it!
- eco 11y agoMicrosoft is also pushing for async/await in C++ in the form of stackless resumable functions complete with an implementation before C++17 has been standardized. http://blogs.msdn.com/b/vcblog/archive/2014/11/12/resumable-functions-in-c.aspx http://blogs.msdn.com/b/vcblog/archive/2014/11/12/resumable-...
- PopsiclePete 11y agoI'm a little sad the async/await model is winning over. I really prefer Go's CSP. It can do everything the async/await model can, plus "streaming" API's. I dig (sorta) C#'s async/await, but I still don't see why it's "winning" over other, better models...
- deleted 11y ago[deleted]
- deleted 11y ago[deleted]
- deleted 11y ago[deleted]
- deleted 11y ago[deleted]
- deleted 11y ago[deleted]
- deleted 11y ago[deleted]
- deleted 11y ago[deleted]
- deleted 11y ago[deleted]
- grayrest 11y agoI wish the we were getting F#'s computation expressions+asynchronous workflows (monad sugar) instead of C#'s async/await.
- ilaksh 11y agohttp://livescript.net/ http://livescript.net/ is more like F# but I don't think it has those features.
- louthy 11y agoYou could try funscript[1]: "F# to JavaScript with type providers FunScript is a lightweight F# library that lets you rapidly develop single-page applications. You can connect to external data sources and call REST APIs with intellisense, produce dashboards using JavaScript visualization libraries and write asynchronous computations easily without explicit callbacks." [1] http://funscript.info/ http://funscript.info/
- tlrobinson 11y agoFor those wanting to use async/await everywhere, right now, it can be transpiled using Babel or similar (in Babel you need to enable the "es7.asyncFunctions" feature: https://babeljs.io/docs/advanced/transformers/#es7-experimental- https://babeljs.io/docs/advanced/transformers/#es7-experimen... )
- AgentME 11y agoCurrent versions of Babel default to having es7.asyncFunctions enabled.
- ilaksh 11y agoSerms like I still need --optional runtime and babel-runtime though, right?
- AgentME 11y agoYou need to do that, or include the global polyfill: https://babeljs.io/docs/usage/polyfill/ https://babeljs.io/docs/usage/polyfill/. If you're writing a library, use the runtime option. If you're writing a website or other standalone app, you should use the polyfill (especially if you use other libraries like React which depend on ES6 globals too).
- mistercow 11y agoAlso, if you're targeting a JS implementation with generators, but no await, Q has an async method that uses generators to achieve the same result, albeit with "yield" instead of "await" (in fact, I believe babel's experimental await support uses generators as an intermediate transform; sure looks like it from the code it generates). This means you can get await-like promise handling in Node.js using the --harmony_generators flag.
- jongleberry 11y agoWe're moving Koa to be ready for async functions. Does anyone know whether async functions will have an arrow function form? https://github.com/koajs/compose/pull/27#issuecomment-144868219 https://github.com/koajs/compose/pull/27#issuecomment-144868...
- hekul 11y agoYes - async functions do have an arrow form: http://tc39.github.io/ecmascript-asyncawait/#prod-AsyncArrowFunction http://tc39.github.io/ecmascript-asyncawait/#prod-AsyncArrow....
- chenglou 11y agoI guess I'll take this occasion to post this: http://journal.stuffwithstuff.com/2015/02/01/what-color-is-your-function/ http://journal.stuffwithstuff.com/2015/02/01/what-color-is-y... Which argues that async/await might not be what we really want in the end. As a user of Promises and async/await in the future, it's a very interesting read!
- skybrian 11y agoIt's a great blog post, but be careful what you wish for. If you have true preemptive threading as in Java or Go, a race condition can happen anywhere. I suspect many JavaScript developers would be sad about not having atomic event handling by default and having to learn to code much more carefully. Even in Java UI frameworks like on Android or Swing, you have an event loop with a single thread, and when spawning another thread you have to deal with special communication layers [1]. True multithreaded UI's seem like an area for research. [1] https://developer.android.com/training/multiple-threads/communicate-ui.html https://developer.android.com/training/multiple-threads/comm...
- HeyImAlex 11y agoYeah, the event loop can be a constraint but it's easier to think about and harder to mess up compared threads or channels. And really how much are you giving up? Most of the things you actually want to wait on have an async api. Maybe I just haven't built complex enough things, but I've never had to reach for web workers because of performance concerns.
- Sephr 11y agoFirefox has had this for over 6 years through my async.js[1] library that relied in JavaScript 1.7's pythonic iterators and generators. The syntax is similar, as you have to mark/encapsulate functions with async() to use the library. 1. https://github.com/eligrey/async.js https://github.com/eligrey/async.js
- iso8859-1 11y agoWhat does your library offer over more popular alternatives such as js-csp, task.js, co, galaxy, or gen-run? [1]: https://github.com/ubolonton/js-csp https://github.com/ubolonton/js-csp [2]: http://taskjs.org/ http://taskjs.org/ [3]: https://github.com/tj/co https://github.com/tj/co [4]: https://github.com/bjouhier/galaxy https://github.com/bjouhier/galaxy [5]: https://github.com/creationix/gen-run https://github.com/creationix/gen-run
- Sephr 11y agoNot much, but every one of those came out years after mine and many of them are based on the same general flow as mine.
- LittleDan 11y agoAnd you can use that sort of library in ES6 because generators were standardized.
- deleted 11y ago[deleted]
- colordrops 11y agoYou may want to consider renaming your library. There's already a very popular lib with the same name: https://github.com/caolan/async https://github.com/caolan/async Edit: it appears that the caolan async lib came out after yours. Sorry for the confusion.
- Sephr 11y agoDon't you mean the other way around? Mine was out years before theirs. They should have googled the words "async.js" (which my lib was the top result for prior to caolan's repo) before naming their project.
- mkozlows 11y agoLeaving the Edge news aside, that article starts off by defining event listeners as callbacks, which is awfully weird.
- swang 11y agoI feel like Microsoft doing this is their new attempt at trying to dominate how the web will be shaped. I know the likelihood of async/await being bundled with ES7/ES2016 is pretty high but lets say it gets delayed for further review, is Microsoft going to wait until these specs are "official" before releasing it into standard non-preview Edge or are they just going to rush it as fast as possible, pat themselves on the back and then shrug their shoulders when their syntax is completely different from the actual ES7 implementation? async/await is important and highly desired by the community, but I would prefer if it were not Microsoft trying to blast ahead and create yet another separate fragmentation between browsers. Sure they call it an experimental feature, but how long until they decide, "well we're not going to wait for this to get finalized, we're releasing it for everyone!!!" ?
- dcherman 11y agoI'd be curious about one potential downside to this (v8 specific, maybe others too) Functions that contain a try/catch cannot currently be optimized by V8. If we migrate to using try/catch rather than `.then/.catch`, I wonder if there's going to be any perf implications since previously optimizable functions may no longer be optimized.
- nowprovision 11y agoDo we have an ES7 compiler to ES6 that can handle these new features? Whilst I prefer cljs, sometimes the weight of clojurescript output and tooling can be a little offputting for smaller tasks, but callbacks/promises etc.. are rarely enjoyed
- indeyets 11y agohttps://babeljs.io/ https://babeljs.io/
- josteink 11y agoBut it's still "just IE", right? Right guys? Seriously though. I think that argument is losing steam every time I do testing with Edge. It gets updated. It feels different. Unless somebody were to tell me both IE and Edge belong to the same browser family, I wouldn't be and to tell. I'd say it's fair to call it a new browser.
- camhenlin 11y agoCanvas performance still pretty awful compared to more modern browsers. Source: http://www.networkworld.com/article/2979845/microsoft-subnet/microsoft-edge-browser-performance-test-chrome-firefox-internet-explorer.html http://www.networkworld.com/article/2979845/microsoft-subnet...
- nvivo 11y agoJust being picky, but because Edge was released after all other browsers, technically there isn't any other "more modern browser". There are just the other browsers.
- eyko 11y agoEdge is not cross platform so those of us who don't have any devices running windows don't have any exposure to it in order to praise it. That said, nobody I know refers to Edge as "just IE"; in fact, it's not even considered IE (the name is Microsoft Edge, right?). In any case it's good news that Windows users will finally have decent browser by default. That is, when Edge adoption/usage is higher than all IE versions combined). My point being: IE is just IE. Edge is Edge and we're happy about it.
- needusername 11y agoIs Edge/IE still the only major browser left that doesn't support server-sent events?
- tkubacki 11y agoI'm heavy Dart with dart2js user. Dart has await/async from few releases It is really a relief when it comes to multiple AJAX/UI dependant logic eg. if(await showDialog("get coffe ?") == "yes"){ results = await getCoffeFromServer(); } else { ... }
- z3t4 11y ago"await" will not help you if you do not understand the asynchronous nature. I think it's a unnecessary abstraction. And it's much easier to follow callbacks if you abstract them like this: socket.on("data", echo); // calls the echo function when data arrives
- moo360 11y agoNow if they would implement the HTML5 file drag & drop api like literally every other modern browser then may be people would actually use Edge.
- Loque 11y agoO the tone of MS harping on about what Edge is doing feels like smoke and mirrors to me whilst IE11 will remain one of our lowest common denominators for some time. I respect that a team would love to forget about IE11, but MS is the only company that has any control over it... so whilst they dazzle people with c# style syntactical sugar and pushing typescript (which we will have to compile down to ES5 anyway) I find it hard to get excited about Edge. Get the basics done right first imvho. I don't want developers staying late to try and understand why something isn't working in a MS browser anymore.