0

My goal is to fetch characters from swapi that played in the movie that I choose.

In the first route

router.get('/task1', movieController.getAllMovies)

I fetch all data about the movie:

exports.getAllMovies = (req, res, next) => {
  axios.get('https://swapi.co/api/films')
    .then(res => {
      filmsArray = res.data.results
      films = filmsArray
    })
    .then(res.render('task1/allMovies', {
      pageTitle: "Movies",
      films: films
    }))
    .catch(err => {
      console.log(err)
    })
}

so in ejs file I can extract id and title. I pass id to my route

<a href="/movie/<%=f.episode_id%>">

The problem is when I want to display character that appeared in the movie. For this I register a new route:

router.get('/movie/:movieId', movieController.getActors)

and in the controller :

exports.getActors = (req, res, next) => {
  const movieId = req.params.movieId
  let actorsData = []
  let actors = []
  axios.get('https://swapi.co/api/films/' + movieId)
    .then(res =>{
      actorsData = res.data.characters
    })
    .then( res => {
      actorsData.map( actor => {
        axios.get(actor)
        .then(res => {
          actors.push(res.data)
        })
      })

      })
    .then(res.render('task1/actors', {
      pageTitle: 'Actors task 1',
      actors: actors
    })
    )
    .catch(err => {
      console.log(err)
    })
}

I am trying to push characters to actors array but it is constantly empty. Why? How to fix it?

At the end I would like to have a array of characters so I can pass it to my ejs file and display it over there.

jakmas
  • 83
  • 1
  • 1
  • 8
  • That `.map` callback doesn't return anything. – VLAZ Jul 25 '19 at 14:14
  • So how it should be done? Simple return won't help, right? – jakmas Jul 25 '19 at 14:20
  • If you are performing a *mapping* operation, then you are transforming each element of an array. If you don't return anything then you're not mapping anything. My guess is that you [are misusing `.map`](https://stackoverflow.com/questions/56903693/is-performing-a-mapping-operation-without-using-returned-value-an-antipattern/56904505#56904505) – VLAZ Jul 25 '19 at 14:22
  • What do you mean that I'm missing .map? there's actorsData.map? Can you please explain it to me because I'm kinda confused ;) ? – jakmas Jul 25 '19 at 14:26
  • Not *missing* but mis**using**. You are using map *without* doing a mapping operation only in order to loop over the array. If that's what you need, then you need `.forEach`. – VLAZ Jul 25 '19 at 14:29
  • ok, I did it and it works only when I will add another promise .then(res => { setTimeout(() => {console.log('actors', actors)}, 1000) }) how to do it without this promise? – jakmas Jul 25 '19 at 14:38

0 Answers0