Roma Kap Roma Kap - 17 days ago 5
Javascript Question

promise call separate from promise-resolution

I'm not so familiar with promises.
I would like hide promise-implementation from promise-call.

Example:

function findFriends(req, res) {

const promiseFriend = MyFriendes.find({}).exec(); //call promise

if(friends.length===0){
logger.warn('No friendsavailible');
}else if(friends === undefined){
res.status(500).json({
error: 'INTERNAL ERROR'
});
}else{
res.status(200).json({
friends: friends
});
}
}


and I will resolve my promise within same file but not
at same function, where I call this promise.

promiseFriend
.then(function(friends){
return friends;
})
.catch(function(err){
logger.error({error:err});
});


Now, I get, that "promiseFriend" is undefined.
How can I separate promise-call from promise-resolution?

rsp rsp
Answer

If you want to define a promise in a function and use it somewhere else then first of all you need to return the promise from that function, which you're not doing in your code. Then you need to actually call that function which you are also not doing. And finally you need to use a then callback on the returned value, which you are not doing in this case as well.

There is no point in saving the promise in a local variable promiseFriend that is scoped to this function. There is also no point to return a value in your then callback: .then(function (friends) { return friends; }) - I have no idea what have tried to do here.

I suppose that findFriends is supposed to be a route handler for Express. If so then make sure that you send a response in every case (which you don't do for friends.length===0). Also, you need to actually add a then handler to the saved promise if you want to act when it's resolved. Right now you don't even have friends defined in your function. Also add a catch handlers and also send a response for that case.

Then you might return the promise from your function but not if it is a route handler, it doesn't make sense. You can return a promise from a function:

function x() {
  return MyFriendes.find({}).exec();
}

and then use it:

x().then(friends => ...).catch(error => ...);

but you cannot use return values if you don't return it, you can't use undefined variables as if they were defined, and you actually need to consider who is your return value returned to.

I suggest that you learn how Node actually works because it seems that you have copied and pasted some random code, joined it together and expect that it does what you want without actually trying to understand it.

To get a better understanding on the asynchronous nature of Node that is giving this execution order here, see those answers:

Don't try to write Node programs before you understand the concept of function calls, return values, callbacks and in this case promises.