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

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

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]

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

try this:


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

about 4 years ago · Juan Pablo Isaza Report
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!