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

259
Views
¿Cómo obtener datos resueltos de la función Promise esperando?

Quiero obtener información sobre el uso de la CPU. Usé la función setTimeout para obtener la información.

Cuando uso let result = getCPUUsage() la consola muestra

getCPUUsage()>> Promise { <pending> }

entonces si hago la línea como let result = await getCPUUsage() , entonces la consola emitió un error y mostró

SyntaxError: await is only valid in async function

Quiero hacer ese result valioso como JSON {avg:<0~100>}. ¿Podría decirme cómo obtener datos JSON resueltos de Promise y hacer que el result sea el JSON resuelto?

 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 answers
Answer question

0

Debe estar dentro de una función asíncrona para usar await .
A menos que esté utilizando ESM con async de nivel superior. No está permitido usar await en el nivel superior del módulo.
Aquí está la solución

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