how to correctly use promises to return 2 different results

176 views Asked by At

I am trying to use Promises in JavaScript using ES6 to return data from 2 methods from an object, which would in production call out to an endpoint.

My MovieApi object I have 2 promises which I want to return firstly a list of movies, and then 1 movie by id. I want to use promises to avoid callback hell. I am following the approach listed as the answer to the question Arent promises just callbacks but I am clearly doing it wrong, as I have the error findMovie is not defined

let movieData = [ 
    {
      id: '1011',
      name: 'Gleaming the cube', 
      year: "1989"
    },
    {
      id: "1012",
      name: "Airborne", 
      year: "1989"
    }
  ]

let MovieApi = {    
  findMovie: function(id) {    
    return new Promise(function(resolve, reject) {
      if(id === undefined) reject(Error('incorrect movie id'));

      let movie = ''
      for (let m of movieData) {
        if (m.id.toLowerCase() === id.toLowerCase()) {
          movie = m
          break
        }
      }
      resolve(movie)
    });
  },
  findAllMovies: function() {
    return new Promise(function(resolve, reject) {    
      if(movieData === undefined) reject(Error('Could not find any movies'))

      resolve(movieData)
    });
  }    
}

Call the movie promise like this... but I get an error trying to call my second .then() method

MovieApi.findAllMovies()
.then( function (movies){
  return findMovie(req.params.id)
}).then(function(movie){
  let MovieStore = { movie: movie, movies: movies }
}).catch(function(error) {
  console.error("Failed!", error);
});

Is there a way to get out of callback hell here, or will I just have to make another call to the MovieApi object, essentially having the same readability issue as if I were using callbacks.

1

There are 1 answers

1
Arun P Johny On BEST ANSWER

The problem is return findMovie(req.params.id), your findMovie is a property of the MovieApi object so

MovieApi.findAllMovies()
.then( function (movies){
  return MovieApi.findMovie(req.params.id)
})

Demo: Fiddle