Say I have following node.js code
function foo() {
return promiseOne().then(function(result) {
return promiseTwo();
});
}
What's the difference between these two "return"s? I know the purpose of 2nd "return" is to make promiseTwo() thenable. Do I have to have the 1st "return"? I guess it comes down to the scope of 2nd "return"? Because if I call foo()
somewhere and I don't have 1st 'return', then I will not get anything back?
What's the difference between these two "return"s?
The first one returns a promise that is returned by the .then()
method call that is invoked on the result of promiseOne()
function call. The second one returns the promise that is returned by promiseTwo()
function call.
Do I have to have the 1st "return"?
No if you don't want the promise to be returned from the foo()
function and yes if you do.
Because if I call foo() somewhere and I don't have 1st 'return', then I will not get anything back?
That's true for any function. If the function doesn't return anything then you will not get anything back. It's true no matter what the function returns - a promise or anything else.
If the foo()
function doesn't return a value then you will not be able to do any of:
let promise = foo();
foo().then(...);
foo().catch(...);
let value = await foo();
try { await foo(); } catch (err) { ... }
The last one would only catch exceptions thrown by the foo()
function itself, it wouldn't catch the promise rejection if you don't return the promise from the foo()
function.