Link to home
Start Free TrialLog in
Avatar of Bruce Gust
Bruce GustFlag for United States of America

asked on

Why does this work?

Here's my code:

exports.deletePost = (req, res, next) => {
  const postId = req.params.postId;
  Post.findById(postId)
    .then(post => {
      if (!post) {
        const error = new Error("Could not find post.");
        error.statusCode = 404;
        throw error;
      }
      //check login user
      clearImage(post.imageUrl);
      return Post.findByIdAndRemove(postId);
    })
    .then(result => {
      console.log(result);
      res.status(200).json({ message: "Deleted post!" });
    })
    .catch(err => {
      if (!err.statusCode) {
        err.statusCode = 500;
      }
      next(err);
    });
};

Open in new window


Line #12, it says return Post.findByIdAndRemove(postId).

I was always under the impression that once you invoke the "return" dynamic, you're exiting the flow of the code at that point. Yet, in this case, it proceeds to the next "then" clause.

Why?

The code works, but I want to know why the continues to the next "then" clause despite the fact that there's a "return" dynamic in place.
Avatar of leakim971
leakim971
Flag of Guadeloupe image

this is promise : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

the question is : how do we send something to the next "executor" parameter
the answer is : use return

something : Post.findByIdAndRemove(postId)
next "executor" parameter : result
Avatar of Bruce Gust

ASKER

So, my confusion, then, stems from the fact that I'm looking at "return" in the context of a conventional function as opposed to the way it's being used her in the context of a callback / promise, yes?
EXPERT CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I get it! So the "return" is not functioning any differently than it normally does in that it still a "disruption." But because it's happening in the context of several functions chained together, the "disruption" is routed to the next link in the chain as opposed to it forcing the trajectory of the code outside the method as a whole.

Correct?
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you!