lundi 25 octobre 2021

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?




Aucun commentaire:

Enregistrer un commentaire