javascript - 关于 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 结束之前返回)。
你能帮助我吗 ?
解决方案
因此,感谢您的一些答复,我更改了代码,但现在我需要弄清楚在获取信息后如何将其发送回发出请求的客户。我所做的改变是好还是坏?
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"});
}
}
推荐阅读
- yolo - 暗网中的数据增强和训练 YOLO
- python-3.x - 如何为 3.x windows 的不同 python 版本安装模块
- swift - 有没有办法在 Xcode 中插入图像?
- android - SubsamplingScaleImageView 和 OutOfMemoryError
- php - Soundcloud API (PHP) 返回“无效授权”
- typescript - 在 NestJS + GraphQL 中实现“命名空间类型”解析器
- python - 在 ListView 中使用过滤后的查询集进行分页
- javascript - 如何在 Gatsby 的查询中限制组中的对象?
- android - 如何在 Android 中运行 AsyncTask?
- php - GROUP_Concat 超链接