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

260
Visualizações
How to get resolved data of Promise function by await?

I want to get CPU usage information. I used setTimeout function to get the information.

When I use let result = getCPUUsage() the console shows

getCPUUsage()>> Promise { <pending> }

so if I make the line like let result = await getCPUUsage(), then console emitted error and showed

SyntaxError: await is only valid in async function

I want to make that valuable result as JSON {avg:<0~100>}. Could you please tell me how to get resolved JSON data from Promise, and make result the resolved JSON?

const os = require("os");

let result = getCPUUsage() // or >> let result = await getCPUUsage()
console.log('getCPUUsage()>>', result)



//Create function to get CPU information
function cpuAverage() {
    //Initialise sum of idle and time of cores and fetch CPU info
    let totalIdle = 0, totalTick = 0;
    let cpus = os.cpus();

    //Loop through CPU cores
    for(let i = 0, len = cpus.length; i < len; i++) {

      //Select CPU core
      let cpu = cpus[i];

      //Total up the time in the cores tick
      for(type in cpu.times) {
        totalTick += cpu.times[type];
       }     

      //Total up the idle time of the core
      totalIdle += cpu.times.idle;
    }

    //Return the average Idle and Tick times
    return {idle: totalIdle / cpus.length,  total: totalTick / cpus.length};
}

// fetch cpu info
function getCPUUsage() {
    return new Promise(async (resolve, reject) => {
        let data = {avg : 0}
        try {
            //Grab first CPU Measure
            let startMeasure = cpuAverage();

            //Set delay for second Measure

            const wait = ms => new Promise(resolve => setTimeout(resolve = () =>{

                //Grab second Measure
                let endMeasure = cpuAverage(); 

                //Calculate the difference in idle and total time between the measures
                let idleDifference = endMeasure.idle - startMeasure.idle;
                let totalDifference = endMeasure.total - startMeasure.total;

                //Calculate the average percentage CPU usage
                percentageCPU = 100 - ~~(100 * idleDifference / totalDifference);

            }, ms));

            await wait(100)
                
            console.log(percentageCPU + "% CPU Usage.");
            data.avg = percentageCPU
            resolve(data)
        }
        catch (e) {
            console.log('getCPUUsage error:', e);
            resolve(false);
        }
    })
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You need to be inside an async function to use await.
Unless you are using ESM with top-level async. You are not allowed to use await on the top level of the module.
Here's the workaround

(async function() {
    let result = await getCPUUsage();
    // ...
})()
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