0

Hello the following code is working. However, I was wondering if there is a way to not repeat the function findMovie in the array which is asynchronous multiple times as I'm currently doing.

var request = require('request-promise');


function findMovie(title){
	return request(`http://www.omdbapi.com/?t=${title}`)
	
	.then(res=>{
		var movie= JSON.parse(res)
		return [movie["Title"], movie["Year"],movie["Genre"]]
	})
}

function loadInitialData(movies){    	
	return Promise.all(movies)
		.then((response)=>{    				
				response.forEach((movie)=>{
					console.log(movie[0])
				})
			})
}

var movies= [findMovie("jason bourne"), findMovie("The Matrix"), findMovie("titanic")];

// Above is the function findMovie being written multiple times to make  it work...

loadInitialData(movies);

3 Answers 3

4

You can use map to run a function on every element of an array and return a new array. So you can have a list of strings, and map it to a list of movies.

var movies= ["jason bourne", "The Matrix", "titanic"].map(function (movie) {
  return findMovie(movie);
});

Now because your function takes a single parameter, you can just pass the function name to map, which neatens it up further

var movies= ["jason bourne", "The Matrix", "titanic"].map(findMovie)
Sign up to request clarification or add additional context in comments.

Comments

0

This doesn't have anything to do with your code and everything to do with whether the API you're calling supports batch requests. If it did, then you could pass all the titles at once in a single request, get a JSON object back with an array of movies in it. Again, only if it support that.

If it's any consolation, all the requests that your findMovie() function are doing will be done in parallel, so they'll be faster than making sequential requests for each movie.

For completeness, this isn't really what DRY (Don't Repeat Yourself) means. DRY refers to not writing the same code over and over when it could be put into a function. If your code wasn't DRY, you wouldn't have the findMovie() and would instead have multiple separate calls to request() in your main code body.

Comments

0

Here's probably the way I'd write it

const request = require('request-promise')

const findMovie = title =>
  request(`http://www.omdbapi.com/?t=${title}`)
    .then(JSON.parse)
    .then(({Title, Year, Genre}) => [Title, Year, Genre])

const findMovies = titles =>
  Promise.all(titles.map(findMovie))

findMovies(["jason bourne", "The Matrix", "titanic"])
  .then(movies => console.log(movies),
        err    => console.error(err.message))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.