1
function addIDS() {
  const imdbIDs = [];
  imdbIDs.push("id1");
  imdbIDs.push("id2");
  ...
  return imdbIDs ;
}

function getThemoviedbIDs(IDs) {
  let arr = [];
  let urls = [];
  for(let i = 0; i < IDs.length; i++) {
    urls.push(`...${imdb_ids[i]}...`);
  }
  $.each(urls, (i, u) => {
    $(function() {
      $.ajax({
        url: u,
        dataType: 'json',
        success: function(data) {
          arr.push(data.tv_results[0].id);
        },
        statusCode: {
          404: function() {
            alert('Err');
          }
        }
      });
    });
  });
  return arr;
}

function getDetails(themoviedbID) {
  console.log(themoviedbID);
  console.log(`...${themoviedbID[0]}`);
}


const imdbIDs = addIDS();
console.log("IMDB IDs: ", imdbIDs);

const themoviedbIDs = getThemoviedbIDs(imdbIDs);
console.log("themoviedbIDs: ", themoviedbIDs);

const themoviedbIDs = getThemoviedbIDs(themoviedbIDs);
console.log("themoviedbIDs: ", themoviedbIDs);

I am using themoviedb database.

populate() I add imdb IDs to the imdbIDs array, then I get themoviedb IDs by getThemoviedbIDs() function.

In the getDetails() function I would like to make ajax request just like in the getThemoviedbIDs() function, but unfortunatelly there is a problem in there. console.log(themoviedbID) output the appropriate array, but console.log(...${themoviedbID[0]}) output .../undefined...

I can get enough information about the series if I am using themoviedb ID.

palloc
  • 323
  • 1
  • 9
  • 2
    That's a super classic question. `getThemoviedbIDs` is asynchronous, but you are assigning it synchronously to a variable, and logging it immediately, so it's necessarily undefined. I have marked the question as a duplicate of https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call. – Jeremy Thille Mar 11 '22 at 15:43
  • @JeremyThille maybe I do not understand it correctly. I put the function call between `(async () => { .... })();` and put `await` before the function call like `const themoviedbIDs = await getThemoviedbIDs(imdbIDs)` but this is not working – palloc Mar 11 '22 at 16:36
  • Yeah but `$.each` is synchronous. By nature, asynchronous stuff can't work inside synchronous methods. My advice: dump jQuery, you really don't need `$.each` and `$.ajax`. Replace `$.each` with `for( ... )` and `$.ajax` with `await fetch(url)`. Also remove the `$(function() {` from your loop, it's got no business at all here (it means "when the document is ready"). – Jeremy Thille Mar 12 '22 at 06:39
  • 1
    https://codepen.io/jeremythille/pen/bGaGGvj?editors=1010 – Jeremy Thille Mar 12 '22 at 07:00

0 Answers0