0

I'm using the movie database API and try to play the trailer on the youtube for that I need the key value from the JSON response. I tried everything but the function either returns a promise or undefined. I tried to use a callback to return the result but that didn't work either.

const fetch = require('node-fetch');
// function declaration 
async function trailer(id, callback) {
  var video = 'https://api.themoviedb.org/3/movie/' + id + '/videos?api_key=' + apiKey +'&language=en-US';
  var key = await fetch(video)
    .then(res => res.json())
    .then(json => callback(json.results[0].key));
}

// function call returns a promise (expected key string ex."Zftx5a")
trailer(id, function(result){return result;})

1 Answers1

-1

Since the fetch function makes an asynchronous call your trailer function returns key before the promise chain resolves. The easiest way of solving that issue is using an async function, so your code would be something like:

async function trailer(id) {
  var video = 'https://api.themoviedb.org/3/movie/' + id + '/videos?api_key=' + apiKey +'&language=en-US';
  return await fetch(video)
    .then(res => res.json())
    .then(json => json.results[0].key);  
}

However, you must take into consideration that an async function will return a promise, so you will have to modify your code.

For further information check the following links:

https://www.npmjs.com/package/node-fetch#common-usage

https://developers.google.com/web/fundamentals/primers/promises

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

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

J. Pichardo
  • 3,077
  • 21
  • 37
  • 1
    If this will also return a promise what difference would it make? Well I tried to modify my code to get a string from the returned promise but nothing seemed to be working. – Faten Rostom Dec 18 '18 at 19:52