6

When I'm using promises to express dependencies between jobs, where the resolved value becomes unimportant, there is some danger that I might be forgetting a return somewhere. Example:

startSomething().then(function() {
  Q.all(tasks.map(function(task) { return task.startIt(); }))
}).then(collectOutput).done();

Here the Q.all returns a promise, and I should have returned that. Not doing so means that by the time collectOutput gets called, all tasks have been started, but there are no guarantees that they finished.

This kind of error results in a race condition, and may be extremely hard to reproduce and track down. So I wonder, is there some tool to help detect and avoid this kind of problem? Perhaps some promise library which warns when a function along the way returns undefined? Or detects promises with no listeners, the way Bluebird does for unhandled rejections?

eis
  • 51,991
  • 13
  • 150
  • 199
MvG
  • 57,380
  • 22
  • 148
  • 276
  • It's worth pointing out that TypeScript can detect this "forgotten return" problem at compile time. That can be more of a change than you are looking for (you asked for a library, you are getting a suggestion to upgrade your language), but in my personal opinion, TypeScript is absolutely a worthwhile investment. – DCoder Dec 23 '15 at 05:21
  • I find that using arrow functions without {} helps, since the return is implicit. E.g. `startSomething().then(() => Q.all(tasks.map(task => task.startIt())))` – jib Dec 23 '15 at 21:38

1 Answers1

2

Actually, bluebird will warn you if you created a promise in a handler but did not return it. If you're willing to drop Q.

Here's a more in-depth explanation about bluebird's warnings

Warning: a promise was created in a handler but none were returned from it This usually means that you simply forgot a return statement

somewhere which will cause a runaway promise that is not connected to any promise chain.

For example:

getUser().then(function(user) {
    getUserData(user);
}).then(function(userData) {
    // userData is undefined
});
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308