What is the difference between JavaScript promises and async await?
Async/Await provide a much nicer syntax in more complex scenarios. In particular, anything dealing with loops or certain other constructs like try
/catch
.
For example:
while (!value) {
const intermediate = await operation1();
value = await operation2(intermediate);
}
This example would be considerably more convoluted just using Promises.
Why is async,await needed when Promises does similar job? Does async,await solve a bigger problem?
async/await
simply gives you a synchronous feel to asynchronous code. It's a very elegant form of syntactical sugar.
For simple queries and data manipulation, Promises can be simple, but if you run into scenarios where there's complex data manipulation and whatnot involved, it's easier to understand what's going on if the code simply looks as though it's synchronous (to put it another way, syntax in and of itself is a form of "incidental complexity" that async/await
can get around).
If you're interested to know, you can use a library like co
(alongside generators) to give the same sort of feel. Things like this have been developed to solve the problem that async/await
ultimately solves (natively).