【发布时间】:2021-11-30 12:31:47
【问题描述】:
我想获取 CPU 使用情况信息。我使用setTimeout函数来获取信息。
当我使用let result = getCPUUsage() 时,控制台显示
getCPUUsage()>> Promise { <pending> }
所以如果我像let result = await getCPUUsage() 这样的行,那么控制台会发出错误并显示
SyntaxError: await is only valid in async function
我想将有价值的result 转换为 JSON {avg:}。能否请您告诉我如何从 Promise 中获取已解析的 JSON 数据,并使 result 成为已解析的 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);
}
})
}
【问题讨论】:
-
您需要分享您编写
let result = await getCPUUsage()的代码,但答案就在错误消息中——您不能在非async函数中使用await。这几乎肯定是How to resolve the Syntax error : await is only valid in async function? 的副本;如果没有,请分享minimal reproducible example 并解释这个问题与链接问题有何不同。祝你好运,编码愉快! -
谢谢,我在那行发表了评论
标签: javascript node.js