Joshua Joshua - 28 days ago 7
Node.js Question

Do I have to fulfil my JavaScript promises?

In a Node.js environment if I do this:

var doNoResolve = true;

function a() {
return new Promise(resolve => {
if (doNotResolve) {
return
}
resolve(10);
});
}

a().then(() => {
// I don't want this getting fired
});


On an incoming request, is this a memory leak? If I was using a plain old callback everything would turn out just fine if I didn't execute whatever callback was supplied, but this feels like it might not be... the very name promise implies this is somewhat wrong.

If I had to I could return a "fake promise" (
return { then: () => {} }
) inside
function a()
rather than a "real promise" if doNotResolve was true, but that feels a bit gross.

The particular use-case is that of an isomorphic React.js application where I don't want HTTP requests actually getting made (but I do want my stores to update to a state that causes, say, a loading icon to appear).

Answer

Why would you do that instead of rejecting?

The benefit of promises is that they allow both resolving and rejecting, which:

  1. Doesn't fire the then handler (unless you provide two callbacks, which is considered bad practice)
  2. Does fire the catch handler, which explicitly handles errors
  3. Still fire the finally handler

You can simply do:

function a() {
    return new Promise((resolve, reject) => {
        if (doNotResolve) {
            reject(new Error('Oh noes!'));
        }
        resolve(10);
    });
}

Any good Promise implementation will give you a stacktrace from the location you called reject to help you debug async code, as well as calling any catch/finally handlers:

a().then(val => {
  console.log('Got data:', val);
}).catch(err => {
  console.error(err);
}).finally(() => {
  console.log('Done!');
});

Never rejecting or resolving a promise will, depending on your implementation, leave it on the stack of pending promises and very likely throw or log an error when your page unloads or the node promise exits. I know Bluebird will complain if you've left any promises pending, since it typically indicates a bug within the async part of your code.