Search code examples
javascriptnode.jsexpressasynchronousreturn

Question about JS Async / Sync return issue


I need some help about some js async/sync stuff. I read a lot of post, youtube video etc and I don't understand my problem. The problem I've got is I use some async functions which are going to return a value after the processing and use this returned value inside the main function to respond to a get call.

I have a NodeJS Express setup, when I go the the specific link my server received a request and execute a function.

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}`);
    });
}

The console.log inside the getCpuInformation is working perfectly because it is waiting the result of the si.currentLoad to write but the console.log inside the server.get write undefined because, I guess, it doesn't wait the return (or the return actually return before the end of si.currentLoad).

Can you help me ?


Solution

  • Try something like this:

    server.get('/info', async (req, res) => {
        //res.send('Hello this is the API for sysinfo!');
        //res.writeHead(200, {'Content-Type': 'application/json'});
        console.log(await getCpuInformation());
    });
    
    async function getCpuInformation() {
        try {
            const data = await si.currentLoad();
            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}`);
        };
    }