3

I have a promise chain inside of a function and I would like to console.log the values returned from 2 functions inside of the chain. How would I do this? With my current code I get the value from si.cpuTemperature() then undefined but I would like to get the value from si.cpu() then 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));
Jordan Baron
  • 3,752
  • 4
  • 15
  • 26

1 Answers1

3

From the docs,

systeminformation.method() returns a promise. So you don't really need to wrap it inside a promise constructor, ie new Promise()

To get the cpu and temperature, since they are not dependent on each other, you can do either use parallel promises along with an async function or just parallel promises

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

  console.log(cpu, temperature)
}

or

function getCpuAndTemperature() {
  return Promise.all([
      si.cpu(),
      si.cpuTemperature()
  ])
  .then(([cpu, temperature]) => {
    console.log(cpu, temperature)
  })
}
Swaraj Giri
  • 4,007
  • 2
  • 27
  • 44