首页 > 解决方案 > 关于 JS Async / Sync 返回问题的问题

问题描述

我需要一些关于 js 异步/同步的帮助。我阅读了很多帖子、youtube 视频等,但我不明白我的问题。我遇到的问题是我使用了一些异步函数,这些函数将在处理后返回一个值,并在主函数中使用这个返回值来响应 get 调用。

我有一个 NodeJS Express 设置,当我转到特定链接时,我的服务器收到了一个请求并执行了一个函数。

server.get('/info', (req, res) => {
    //res.send('Hello this is the API for sysinfo!');
    //res.writeHead(200, {'Content-Type': 'application/json'});
    console.log(getCpuInformation());
});

function getCpuInformation() {
    si.currentLoad()
    .then(data => {
        var cpuUsage = Math.round(data.currentload);
        console.log(`CPU Usage : ${cpuUsage}%`);
        return cpuUsage;
    })
    .catch(error => {
        console.error(`Error during the request of the CPU : ${error}`);
    });
}

getCpuInformation 中的 console.log 运行良好,因为它正在等待 si.currentLoad 的结果写入,但 server.get 中的 console.log 写入未定义,因为我猜它不等待返回(或return 实际上在 si.currentLoad 结束之前返回)。

你能帮助我吗 ?

标签: javascriptnode.jsexpressasynchronousreturn

解决方案


因此,感谢您的一些答复,我更改了代码,但现在我需要弄清楚在获取信息后如何将其发送回发出请求的客户。我所做的改变是好还是坏?

server.get('/info', (req, res) => {
    //res.send('Hello this is the API for sysinfo!');
    getAllInformation((resultReturned) => {
        console.log(resultReturned);
    });
});

async function getAllInformation(myCallBack) {
    var cpuUsage = await getCpuInformation();
    // more inc
    myCallBack(cpuUsage);
}

async function getCpuInformation() {
    try {
        const data = await si.currentLoad();
        var cpuUsage = Math.round(data.currentload);
        //console.log(`CPU Usage : ${cpuUsage}%`);
        return JSON.stringify({ "cpuUsage": cpuUsage});
    } catch(error) {
        //console.log(`Error during the request of the CPU : ${error}`);
        return JSON.stringify({ "cpuUsage": "ERROR"});
    }
}

推荐阅读