Categories
Posts

Do You Keep Your Promises?

Asynchronous JavaScript is not easy. There has been a strong push towards promises ( hello ES6! ). Unfortunately they also introduce some new side effects, which may not be immediately obvious. Nolan Lawson covers a number of these in We have a problem with promises.

In the end:

That being said, promises aren’t perfect. It’s true that they’re better than callbacks, but that’s a lot like saying that a punch in the gut is better than a kick in the teeth. Sure, one is preferable to the other, but if you had a choice, you’d probably avoid them both.

While superior to callbacks, promises are still difficult to understand and error-prone, as evidenced by the fact that I felt compelled to write this blog post. Novices and experts alike will frequently mess this stuff up, and really, it’s not their fault. The problem is that promises, while similar to the patterns we use in synchronous code, are a decent substitute but not quite the same.

If you are in the world of JavaScript callbacks and promises, you’ll really want to check out Taming the asynchronous beast with ES7 ( also by Nolan Lawson ).

Going to ES7 brings async and await ( hopefully ). Being able to write code that conceptually looks synchronous is very appealing:

[sourcecode lang=”javascript”]
let db = new PouchDB(‘mydb’);
try {
let result = await db.post({});
let doc = await db.get(result.id);
console.log(doc);
} catch (err) {
console.log(err);
}
[/sourcecode]

This of course introduces yet another set of issues that you have to be aware of. That said, this feels like the right direction.