获取承诺链的两个 return 个值

Get both return values of a promise chain

我在函数内部有一个承诺链,我想 console.log 从链内部的 2 个函数返回的值。我该怎么做?使用我当前的代码,我从 si.cpuTemperature() 然后 undefined 获取值,但我想从 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,

systeminformation.method()returns一个承诺。所以你真的不需要将它包装在一个 promise 构造函数中,即 new Promise()

要获得 cpu 和温度,因为它们彼此不依赖,您可以使用并行承诺和异步函数,或者只使用并行承诺

async function getCpuAndTemperature() {
  const [cpu, temperature] = await Promise.all([
      si.cpu(),
      si.cpuTemperature()
  ])

  console.log(cpu, temperature)
}

function getCpuAndTemperature() {
  return Promise.all([
      si.cpu(),
      si.cpuTemperature()
  ])
  .then(([cpu, temperature]) => {
    console.log(cpu, temperature)
  })
}