How to get the output as a (global) variable from Promises in JavaScript? I found many answers but none helped me in applying to my problem. Specifically, I want to get the data from the code below. It is the node-os-utils
library.
cpu.usage()
.then(info => {
console.log(info)
})
EDIT:
I tried to edit the code according to your recommendations, unfortunately I still couldn't find where I'm making a mistake.
I used the async
function with await
. Now I would like to return and display the value in systemdata
, but the output shows Promise <pending>
. I figured it's probably because the object is running in the stack before promise
completes.
cpu.usage()
.then(cpuPercentage => {
return cpuPercentage +'%';
});
const printCpuUsage = async () => {
const a = await cpu.usage();
return a;
};
let systemdata = {
cpuCount: cpuCount,
cpuModel: cpuModel,
cpuUsage: printCpuUsage(),
// memoryUsage: ,
// CPUtemp: ,
// batteryCycle: ,
// StorageSize:
};
console.log(systemdata)
So I tried to put async
directly into the object. With the assumption that this way the object property will have to wait for a promise
.
const cpuusage = cpu.usage()
.then(cpuPercentage => {
return cpuPercentage +'%';
});
let systemdata = {
cpuCount: cpuCount,
cpuModel: cpuModel,
cpuUsage: async () => {
const a = await cpuusage;
return a;
},
// memoryUsage: ,
// CPUtemp: ,
// batteryCycle: ,
// StorageSize:
};
console.log(systemdata)
Unfortunately this code output: cpuUsage: [AsyncFunction: cpuUsage]