How to call a function within function?

Asked

Viewed 56 times

1

I’m developing a API, and in it I need to implement a method that seeks within my database a film through your ID.

As I will use this method to perform more than one time, I would like to reuse it in my code. For this I implemented the following code that consults the ID applied for:

async function findMovie(req, res, next){
    let movie;
    try {
      movie = await Movie.findById(req.params.id);
      if (movie == null) {
        return res.status(404).json({ message: "Cannot find Movie" });
      }
    } catch (err) {
       return res.status(500).json({ message: err.message });
    } 
    res.movie = movie;
    next();
}

Having done so, I implemented another method that runs the findMovie() when an ID is requested through the URL:

localhost:3000/Movies/5e7688cb534f364cf269c010

const getMovie = (req, res) => {
    const m = m.findMovie()
    res.json(res.m)
}
  • The title and the body is not making sense ... has how to explain better?

  • @Virgilionovic needs to invoke the function findMovie inside getMovie, but the above code is not working. I believe the way I’m calling the function findMovie is incorrect.

1 answer

1

@Virgilionovic needs to invoke the function findMovie inside getMovie, but the above code is not working. I believe the way I’m calling the function findMovie is incorrect

By the user comment failed to sign the method with async and in the promisse await example:

const getMovie = async(req, res) => {
    const m = await m.findMovie();
    res.json(res.m);
}

to await the outcome of an asynchronous method. A good read has here on the site the explanation of async/await

Browser other questions tagged

You are not signed in. Login or sign up in order to post.