简体   繁体   中英

Array iteration using for-each in javascript

function getCredits(movie) {
  let count = 0;
  let cast_ids = [];
  let movie_id = movie;
  console.log("movie_id arr.len-- ", movie_id.length);

  movie_id.forEach((movieid, index) => {
    let api_url = domain + 'movie/' + movieid + '/credits' + '?api_key=' + key;
    http.get(api_url, function (response) {
      let total_data = '';
      response.on('data', (temp_data) => total_data += temp_data);
      response.on('end', () => {
        const parsedData = JSON.parse(total_data);
        if (typeof parsedData.id !== 'undefined') {
          count = count + 1;
          console.log("mid.ind: ", index);
          console.log("mid: ", parsedData.id);
          console.log("len: ", parsedData.cast.length);
          console.log("count : ", count);

          parsedData.cast.forEach(castid => {
            if (cast_ids.indexOf(castid.id) == -1) {
              cast_ids.push(castid.id)
            }
          })
          console.log("c: ", cast_ids.length);
        }
      })
    })
  })
}

I have an array named 'movie' of length 40 (Generated from call to an API) but using forEach, am unable to iterate through all the elements in that array. I have read that the order of iteration using forEach occurs in the insertion order but when I print the indexes I find it not. The iteration occurs in random order and am able to Traverse through only 38 elements in the array.

Output--

movie_id arr.len-- 40

mid index:  8
mid:  27205
len:  29
count :  1
c:  29

mid index:  16
mid:  398818
len:  13
count :  2
c:  42

mid index:  6
mid:  375098
len:  16
count :  3
c:  58

mid index:  31
mid:  446791
len:  31
count :  4
c:  89

mid index:  27
mid:  372058
len:  13
count :  5
c:  102
    .
    .
.
.
count :  37
c:  1470
mid index:  3
mid:  335984
len:  28
count :  38
c:  1496
Process finished with exit code 0

You need to wait for the request to complete before doing further task, for that need to use async or do callbacks.

As http library does not return a promise you cannot use async/await directly, a promise wrapper function can be made to return a promise. Try this,

async function getCredits(movie) {
  let count = 0;
  let cast_ids = [];
  let movie_id = movie;
  console.log("movie_id arr.len-- ", movie_id.length);

  movie_id.forEach((movieid, index) => {
    let api_url = domain + 'movie/' + movieid + '/credits' + '?api_key=' + key;

    let total_data= await processMe(api_url); //below execution will stop untill total_data is not fetched
    const parsedData = JSON.parse(total_data);
        if (typeof parsedData.id !== 'undefined') {
          count = count + 1;
          console.log("mid.ind: ", index);
          console.log("mid: ", parsedData.id);
          console.log("len: ", parsedData.cast.length);
          console.log("count : ", count);

          parsedData.cast.forEach(castid => {
            if (cast_ids.indexOf(castid.id) == -1) {
              cast_ids.push(castid.id)
            }
          })
          console.log("c: ", cast_ids.length);
        }


  })
}

function processMe(api_url){

 return new Promise(function(resolve,reject){
      http.get(api_url, function (response) {
        let total_data = '';
        response.on('data', (temp_data) => total_data += temp_data);
        response.on('end', () => {
          resolve(temp_data);       
        })
        response.on('error',(err)=>{
          reject(err);
        })
     }) 

 });


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM