我在函数内部有一个Promise链,我想console.log从链中2个函数返回的值.我该怎么做?使用我当前的代码,我从si.cpuTemperature()获取值,然后未定义,但我想从si.cpu()然后从si.cpuTemperature()获取值.
const si = require('systeminformation');
function getcpuInfo() {
return new Promise((resolve) => {
resolve();
console.log("Gathering cpu information...");
return si.cpu()
// .then(data => cpuInfo = data) - no need for this,the promise will resolve with "data"
.catch(err => console.log(err)); // note,doing this will mean on error,this function will return a RESOLVED (not rejected) value of `undefined`
})
.then(() => {
return si.cpuTemperature().catch(err => console.log(err));
});
}
getcpuInfo().then((data1,data2) => console.log(data1,data2));
最佳答案
从docs开始,
原文链接:https://www.f2er.com/js/531296.htmlsysteminformation.method()返回一个promise.因此,您实际上不需要将其包装在promise构造函数中,即new Promise()
要获取cpu和温度,因为它们彼此不依赖,所以可以将并行承诺与异步函数一起使用,也可以只使用并行承诺
async function getcpuAndTemperature() {
const [cpu,temperature] = await Promise.all([
si.cpu(),si.cpuTemperature()
])
console.log(cpu,temperature)
}
要么
function getcpuInfo() {
return Promise.all([
si.cpu(),si.cpuTemperature()
])
.then(([cpu,temperature]) => {
console.log(cpu,temperature)
})
}