在JavaScript中使用for-each进行数组迭代

时间:2018-08-05 15:49:15

标签: javascript arrays node.js api

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);
        }
      })
    })
  })
}

我有一个名为“电影”的数组,长度为40(从对API的调用生成),但是使用forEach,无法迭代该数组中的所有元素。我已经读到,使用forEach进行迭代的顺序是按插入顺序发生的,但是当我打印索引时却没有发现。迭代以随机顺序发生,并且只能遍历数组中的38个元素。

输出-

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

1 个答案:

答案 0 :(得分:0)

您需要等待请求完成后再执行其他任务,因为这需要使用异步或执行回调。

由于http library不返回承诺,因此您不能直接使用async / await,因此可以使promise wrapper function返回承诺。 试试这个,

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);
        })
     }) 

 });


}