awaits versus promises

I’ve seen both types of codes flying around.

promises
https://docs.maidsafe.net/safe_app_nodejs/

awaits
https://hub.safedev.org/platform/web/

Which is better?
If awaits are better, how do I catch exceptions?

I would say await can make the code more readable because with Promises you can get a lot of nesting. But it is easy to make a mistake, forgetting to await for example, so you need to be careful.

If awaits are better, how do I catch exceptions?

Wrap you code inside try /catch:

 let x
 try {
    x = await thing()
 } catch (e) {
    console.log ('oops!')
 }

I use both forms, but mostly await because I find it easier to read.

2 Likes

Promises and awaits use the same underlying mechanism! await is just a nice syntax (‘syntactic sugar’) to make using Promise more readable. Without Promise there would be no await.

I think you mean using the .then method that involves callbacks. Like @happybeing says it results in nesting and that might get ugly/unreadable quickly.

For a developer using the APIs make use of await/async as much as possible. Just know what it does and how to use them efficiently. There are cases where running them in parallel (using raw Promises and waiting for them) is better.

2 Likes

Someone should rewrite the docs then.
It uses promises.

1 Like

I just stumbled on the following async cheatsheet that could be useful.

3 Likes

This topic was automatically closed after 60 days. New replies are no longer allowed.