Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

305
Vistas
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 Respuestas
Responde la pregunta

0

try this:


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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda