love love - 6 months ago 22
Node.js Question

Break Out of Function After Returning Promise - JavaScript

When you have a Promise based function like so:

function foo() {
return new Promise(function(fulfill, reject) {
// Do some async work, and then...
console.log('a');
fulfill('b');
console.log('c');
});
}


You'll notice that
c
will get printed after the
fulfill
statement, implying that the function does not break upon fulfill or reject. This is troublesome since most logic would assume that the function should end once it has called
fulfill()
or
reject()
.

Question:

Is it safe or standard usage to then simply add
return
before the
fulfill()
or
reject()
call?


function foo() {
return new Promise(function(fulfill, reject) {
// Do some async work, and then...
console.log('a');
return fulfill('b');
console.log('c'); //Does not get printed, as the function has ended execution.
});
}

// Call the function:
foo()
.then(function(response) {
console.log(response); //This is called once the function calls fulfill, will print 'b'
});


Are there any issues with using Promises like that? Most promise information online makes no reference to using the
return
statement before fulfill or reject. As an additional side question, what is the most common way to use indentation when using
then
and
catch
?

Answer

Generally, in NodeJS, you shouldn't use the promise constructor very much.

The promise constructor is for converting APIs that don't return promises to promises. You should consider using a library that provides promisification (even if you use native promises all-around) since it provides a safe alternative that does not have subtle errors with error-handling logic.

Automatic promisification is also considerably faster.

That said, the answer to your question is "Yes".

It is perfectly safe to do so, there is nothing special about promise constructors - they are just plain JavaScript. Domenic discusses the design of the promise constructor in his blog.

It is perfectly safe (just like any other function) to return early - it is actually quite common in regular asynchronous functions.

(Also, in your example code you should just use Promise.resolve, but I assume it was that simple only because it is an example).