3 ms·
What's the difference between async/await and a future? I've only used futures, but async/await looks like exactly the same thing: You're forking a thread (gree
by tormeh 10y ago
What's the difference between async/await and a future? I've only used futures, but async/await looks like exactly the same thing: You're forking a thread (green or otherwise) to do some stuff and to set a flag of some sort when it's done so you can check on it. Right?
- sreque 10y agoAt a high-level, async/await lets you write non-blocking code as if it were blocking. Golang has a huge advantage here because the runtime was built from the ground up so that everything is non-blocking and the language has built-in support for operations that look like they block, but underneath the hood they don't actually block a thread. Futures are interesting, but at the end of the day they are basically not that different from callbacks. Instead of writing a function that takes a callback, you write a function that returns a future that you essentially register callbacks onto. In Java 8 this type is called a CompletionStage. In fact, in one of Scala's coursera courses they teach you how to take callback-oriented code and convert it into code that returns futures. The fact that it is so easy to convert between the two helps illustrate that futures aren't really adding much. Yes you can compose using flatMap, but, again, I don't think this makes the code that much easier to write, or, more importantly, debug and maintain. As an example, at $lastjob I converted a blocking networking library to a non-blocking one. I started out using futures but I found that it generated a lot of Lambdas, which made debugging much harder because the stacktraces were long and incomprehensible. I ended up switching to callbacks and used named, not anonymous classes to improve readability. Not only did the code feel easier to read and debug but I got better performance out of the library due to reduced memory pressure.
- linkmotif 10y agoIt's the same but you just write top-down linearly as though all the code is on one stack frame, but the runtime performs the stack continuations when async calls return. If you're familiar with JS, read about how babel implements ES7's async/await by wrapping promises. And then try it out. It's awesome.