【问题标题】:How to get resolved data of Promise function by await? [duplicate]如何通过 await 获取 Promise 函数的解析数据? [复制]
【发布时间】: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);
        }
    })
}

【问题讨论】:

标签: javascript node.js


【解决方案1】:

您需要在异步函数中才能使用await
除非您将 ESM 与顶级异步一起使用。不允许在模块顶层使用await
这是解决方法

(async function() {
    let result = await getCPUUsage();
    // ...
})()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 2019-04-24
    • 2019-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    相关资源
    最近更新 更多