Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

99
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!