How to get the output as a variable from Promises in JavaScript?

Hello,

I’d like to ask you. How to get the output as a (global) variable from Promises in JavaScript? Specifically, I want to get the data from the code below. It is the node-os-utils library. My goal is to store the value of cpu.usage in a variable and then insert the variable as a property into an object from which a JSON file will be created and required on the client-side of a certain program. I have tried this:

// global scope
let globalInfo;
cpu.usage().then(info => {
  globalInfo = info;
});

let systemdata = {
  cpuCount: cpuCount,
  cpuModel: cpuModel,
  cpuUsage: globalInfo,
  // memoryUsage: ,
  // CPUtemp: ,
  // batteryCycle: ,
  // StorageSize: 
};

let data = JSON.stringify(systemdata);
fs.writeFileSync('systemdata.json', data);

It returns undefined. I think it is because the value is not loaded into the variable in time. So maybe it would help to set the interval so that the code is asynchronous?

Thank you so much for your time. :innocent:

I even tried something like this:

const cpuUsage = cpu.usage().then(cpuPercentage => {
      return cpuPercentage +'%';
  });

const printCpuUsage = () => {
  cpuUsage.then((a) => {
    return a;
  });
};
let systemdata = {
  cpuCount: cpuCount,
  cpuModel: cpuModel,
  cpuUsage: printCpuUsage(),
  // memoryUsage: ,
  // CPUtemp: ,
  // batteryCycle: ,
  // StorageSize: 
};
console.log(systemdata)

Output:

{
  cpuCount: 12,
  cpuModel: 'AMD Ryzen 5 5600H with Radeon Graphics',
  cpuUsage: undefined
}

What am I doing wrong, please?

cpu.usage() is aynchronous (global scope)
and
fs.writeFileSync( ) is synchronous (global scope)
so I guess fs.writeFileSync( ) would run before cpu.usage()

I’d try to put it all into the callback function in .then

cpu.usage().then(info => {
  
  let systemdata = {
    cpuCount: cpuCount,
    cpuModel: cpuModel,
    cpuUsage: info,
    // memoryUsage: ,
    // CPUtemp: ,
    // batteryCycle: ,
    // StorageSize: 
  };

  let data = JSON.stringify(systemdata);
  fs.writeFileSync('systemdata.json', data);
});

but I don’t know anything about cpu.usage() so this may cause some unexpected problems.

1 Like

You’re great. This solved my problem and now I know how to do it.

Thank you very much again!