【发布时间】:2021-03-01 21:44:03
【问题描述】:
我需要一些关于 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 写入未定义,因为我猜它不会等待返回(或者返回实际在 si.currentLoad 结束之前返回)。
你能帮帮我吗?
【问题讨论】:
标签: javascript node.js express asynchronous return