4 ms·
Personally I find it’s the other way around. Promises are so easy to understand. They are literally that: the promise of a result that you can await later on.
by crubier 6y ago
Personally I find it’s the other way around. Promises are so easy to understand. They are literally that: the promise of a result that you can await later on.
Maybe another helpful way to see it is that each sync function is one atomic block that is executed in one go. On the other hand, see each « await » in an async function as a split of the function into atomic blocks that can be executed separately, allowing to do other things while waiting between each block.
This abstraction catches up because it works really well. It is very composable as well. For example adding a queue instead of naively processing a lot of promises at once is 2 lines of code with this https://www.npmjs.com//promise-queue https://www.npmjs.com//promise-queue
Now I am waiting for async generators to catch up as well, to replace streams... I recently worked with this package for example and it was so much better than plain streams https://www.npmjs.com/package/streaming-iterables https://www.npmjs.com/package/streaming-iterables
- pansa2 6y ago> Promises are so easy to understand. I still don't understand promises in JavaScript. I got my head around the convoluted constructor (a function whose argument is a function whose arguments are two functions), but I can't make sense of chaining and the "promise resolution procedure" [0]. However I've looked into async-await in Python and it seems straightforward. Doesn't `await foo()` just mean "suspend execution here and don't run any more code in this function until foo is done"? [0] https://promisesaplus.com/#the-promise-resolution-procedure https://promisesaplus.com/#the-promise-resolution-procedure
- vorticalbox 6y agoYes and that's what a promise is in a javascript. When you call await on a function it gets put into the event loop and when it's read the processing in the function will resume.
- tehlike 6y agoIn recent versions of javascript, you can use almost the same async/await concept. It's the same thing, it's just that original syntax of promise is a bit too verbose.
- crubier 6y agoAsync await in python and in JS work exactly the same way (except that you have to explicitly launch an event loop in python). I have developed a library that makes heavy uses of promises and async generators, and the code for the python and JS version are extremely similar. Like similar enough that an automatic translation could be done. And yes, forget about .then and other old school stuff like that in JS. Just use async await to deal with promises.