Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

307
Visualizações
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 Respostas
Responde à pergunta

0

try this:


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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda