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

98
Visualizações
Using an exported Object variable inside a promise

I have two javascript files that I am working on. On one of the files (file1.js), I have at the bottom a line for exporting an object-key variable.

module.exports = {randomData};

On the other file (file2.js), I have it included as such at the top:

const {randomData} = require('./file1.js');

Now, when I try to use this {randomData} object in one of my Promise parts in file2.js, it remains undefined as value. I realize that this is because the Promise code is running before the exporting part of file1.js has even finished executing to actually provide {randomData} with any values. I am trying to wrap things with Promises/asyncs/awaits but I'm not getting anywhere. I tried the below, thinking that it would work.

    var randomData = {};

function printRandomData(){
  setTimeout(() => {
        console.log(randomData);
    }, 1000);
}

function fetchRandomData(){
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            randomData = require('./file1.js');

            if(randomData){
                resolve();
            }
            else{
                reject('Error: Something went wrong!')
            }
        }, 2000);
    })
}

async function init() {

  await fetchRandomData(); // wait until the promise resolves (*)

  printRandomData(); // "done!"
}

init();

I'm expecting the above code to run printRandomData() last, to then output the value of randomData, which at that point should have been set to a different value from the fetchRandomData() method. However, this is not the case as the print results in an empty object. Printing from file1.js will show that randomData contains values however.

How do I make the require part happen first before anything else happens in file2.js?

about 4 years ago · Juan Pablo Isaza
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