Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NodeJs javascript: wait until the previous object property is assigned before assigning the next property

Suppose I have code like this:

let result = {
  name: downloadNameFromInternetVerySlow(),
  isFamous: determineIfNameIsFamous(this.name);
}
const downloadNameFromInternetVerySlow = () => {
    path = "/home";
    const folders = fs.readdirSync(path).filter(file => fs.lstatSync(path).isDirectory());
    console.log(folders);
    return folders[0];
}

downloadNameFromInternetVerySlow can take a long time, meanwhile determineIfNameIsFamous depends on downloadNameFromInternetVerySlow‘s result to return correct value.

How do I make sure determineIfNameIsFamous only runs after downloadNameFromInternetVerySlow is done?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The code you show is entirely synchronous so asynchronous results aren’t actually the issue here like people were guessing. The issue is that this.name cannot be used to refer to a prior property in an object literal definition for several reasons, not the least of which this isn’t set to the object you want.

Instead, you can do this:

let result = {};
result.name = downloadNameFromInternetVerySlow();
result.isFamous = determineIfNameIsFamous(result.name);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading