There is an awesome article about that by Gokul N K which I agree with pretty much:
https://hackernoon.com/should-i-use-promises-or-async-await-126ab5c98789
From my point of you, I'd say async/await
is just better in terms of waiting for promise resolves (async function returns promises, btw).
For example, I use async/await
more frequent in node environment when I call async function that manipulate data (DB or 3rd party API). Like:
// server
async function removeComment(commentId) {
const comment = await getComment(commentId);
if (comment) {
const commentAuthorUserId = await getUser(comment.userId);
notifyUser(commentAuthorUserId);
await removedCommentFromDB(comment);
res.json({ status: 'ok' });
}
}
The code above is not real, but shows how cool the code looks without multiple then
nesting. Btw, use try ... catch
for error handling when you use await
many times (more than twice) in one async
function. Otherwise, you can use .catch()
for await promise as @Bergi mentioned.
In other hand, I use Promises in browser to control flow, but not manipulating data.
For example:
// client
function onRemoveClick(commentId) {
service.removeComment(commentId).then(() => {
DOM.removeCommentElement(commentId);
});
}
because If I'd use await
it turns into:
async function onRemoveClick(commentId) {
const response = await service.removeComment(commentId);
if (response.status === 'ok') {
DOM.removeCommentElement(commentId);
}
}
which is a quite longer and also it always resolves a HTTP Response which is not obvious for the first glance.