-1

I need to make this code return a promise. Idk how to do that and i wanna learn. If you can, i would also need some explications, thanks!

var url = "....";

function showMoviesList(callbackFunction){
  fetch(url + "/movies", {
    method: "GET",
    headers: {
        "Content-Type": "application/x-www-form-urlencoded"
    }
  }).then(function(response){
    return response.json();
  }).then(function(moviesArray){
    callbackFunction(moviesArray);
  });
}
Wiktor Zychla
  • 47,367
  • 6
  • 74
  • 106
Andrew
  • 11
  • `"Content-Type": "application/x-www-form-urlencoded"` is nonsense. You are making a GET request. There is no request body to describe the type of. – Quentin Apr 17 '20 at 17:37

3 Answers3

0

fetch already returns a promise. So just return the return value of that, and get rid of everything related to the callbackFunction variable.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

This would be

var url = "....";
function showMoviesList(callbackFunction){
  return fetch(url + "/movies", {
    method: "GET",
    headers: {
       "Content-Type": "application/x-www-form-urlencoded"
  }
  }).then(function(response){
    return response.json();
  });
}
Wiktor Zychla
  • 47,367
  • 6
  • 74
  • 106
0

So return the fetch, make then return the json and you can use .then() with your function call.

var url = "....";

function showMoviesList(callbackFunction) {
  return fetch(url + "/movies").then(function(response) {
    return response.json();
  });
}

showMoviesList.then(function(json) {
  console.log(json);
})
epascarello
  • 204,599
  • 20
  • 195
  • 236