Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

282
Visualizações
How can I get the data of an array in which I m storing in array after running a loop of promises. And export that data in another node file?

I m making a music website. I want to make a trending section. To make that trending section I m using YouTube API to get the no. of views. So here first I m calling my database in which album data is stored. In that one field is such that stores the id of song present in that album. So using that id, I m running a function which gives me no. of views. I am storing that song's id and views in arr_song and arr_views respectively. I then want to export this arr_song and arr_views in my main index file. But the problem is the data is stored in array but as it is a promise the data is getting stored in arr_song and arr_views late and before only it runs in my main index.js file. So eventually it shows me array with nothing. I want to export stored array data in my index.js file.

const axios = require("axios").default;
var url =
  "https://youtube.googleapis.com/youtube/v3/videos?part=statistics&id=";
var key = "&key=AIzaSyDwUGeRKMTCeslgQjETBgP1ozqlB0yX9s0";
var id = "sAzlWScHTc4";
var final_url;
var arr_song = [];
var arr_views = [];

function getYTData(songId) {
  final_url = url + songId + key;
  axios.get(final_url).then(res => {
    const yt_data = res.data;
    console.log(songId);
    console.log(yt_data.items[0].statistics.viewCount);
    arr_song.push(songId);
    arr_views.push(yt_data.items[0].statistics.viewCount);
  });
}

function getting_data() {
  axios.get("http://localhost:8000/albums/").then(res => {
    const album_data = res.data;
    for (var i = 0; i < album_data.length; i++) {
      for (var j = 0; j < album_data[i].songs_id.length; j++) {
        getYTData(album_data[i].songs_id[j]);
      }
    }
  });
}
getting_data();
const ArrSong = arr_song;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Maybe you can export the Promise contains the array using Promise.all function.

// data.js
const axios = require("axios").default;

// return a promise contains an item
function getYTData(songId) {
  return axios.get(final_url).then(res => {
    let data;
    // ...

    return data;
  });
}

exports.promise = axios.get().then(res => {
  let promises = [];
  const album_data = res.data;
  for (var i = 0; i < album_data.length; i++) {
    for (var j = 0; j < album_data[i].songs_id.length; j++) {
      // save all the promises, each contains an item
      promises.push(getYTData(album_data[i].songs_id[j]));
    }
  }
  // pass all promises' items to the variable `promise`
  return Promise.all(promises);
});
// index.js
const { promise } = require("./data.js");

// the data passed from the `promises`
promise.then(data => {
  console.log(data);
});

Note that the data.mjs can only be excuted once. That means no matter how many times you import { promise } from "data.mjs", you still get the same promise contains the same data.

If you want to refresh the data, you should export a function like this

// data.js

// ...

function get_data() {
  return axios.get().then(res => {
    let promises = [];
    const album_data = res.data;
    for (var i = 0; i < album_data.length; i++) {
      for (var j = 0; j < album_data[i].songs_id.length; j++) {
        promises.push(getYTData(album_data[i].songs_id[j]));
      }
    }
    return Promise.all(promises);
  });
}

module.exports = {
  get_data,
};

And then you can get a promise by calling the function. Each time you call the function, you get a new promise contains the latest data.

// index.js
const { get_data } = require("./data.mjs");

get_data().then(data => {
  console.log(data);
});

By the way, your code doesn't work, also because the file can only be executed once.

You should know axios is an asynchronous function.

When you import the file, the synchronous code is being executed.

At this moment, the array is indeed an empty array.

After the file being executed, the array is saved in the module system permanently as a const variable. It can never be changed.

Therefore, you get an empty array.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda