0

Here is my module where, x is returned as undefined.

const si = require('systeminformation');

async function systemData() {
  try {
    let data = await si.system()
    return {
      manufacturer: data.manufacturer,
      model: data.model
    }
  } catch (err) {
    console.log(`${err}`)
  }
}

function checkSystemData() {
  (async () => {
    let sd = await systemData()
    if (sd.manufacturer === 'X') { // Many more such checks

    } else {
      return { check: false, manufacturer: sd.manufacturer }
    }
  })()
}

let x = checkSystemData()
console.log(x)

The checkSystemData() cannot be made async by its author as it is a part of a larger module. HOw do I refactor this to receive x as { check: false, manufacturer: sd.manufacturer }?

cogitoergosum
  • 2,309
  • 4
  • 38
  • 62
  • This is simply not possible. You cannot immediately get the result of an asynchronous task. – Bergi Sep 06 '20 at 23:29
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Roamer-1888 Sep 06 '20 at 23:29
  • You will need to find a synchronous version of `si.system()` if you need `checkSystemData` to synchronously return a result. But really, you *should* make it asynchronous, and have the users of the function deal with that. – Bergi Sep 06 '20 at 23:30
  • @Bergi this is an existing project with some 'history' to it. So, the consequences are quite high and I am hoping to minimize the 'blast radius'. :) – cogitoergosum Sep 07 '20 at 03:25
  • @Roamer-1888 it does. I was hoping I could get a resolved output from `checkSystemData()`. – cogitoergosum Sep 07 '20 at 03:26
  • 1
    As Bergi says, simply not possible. Asynchronously derived data can't be returned synchronously. Introducing an intermediate function won't solve it. – Roamer-1888 Sep 07 '20 at 04:29

1 Answers1

0

You need to return something from checkSystemData()

return (async () => { // add return
  let sd = await systemData()
  if (sd.manufacturer === 'X') { // Many more such checks

  } else {
    return { check: false, manufacturer: sd.manufacturer }
  }
})()

then you can use

checkSystemData().then(response => {
  console.log(response)
})

or

let x = await checkSystemData()
Stevetro
  • 1,933
  • 3
  • 16
  • 29
  • Is it not possible to get a resolved output from `checkSystemData()` - so that, I do not have to `.then` or `await`? – cogitoergosum Sep 07 '20 at 02:10
  • Nope, it returns a Promise which means the value will be available *later*. ```.then``` waits for this result and calls the function, while ```await``` stops the function and returns the value, but is only available in async functions. You can not get a synchronous answer from an async function. – Tamás Sallai Sep 07 '20 at 12:13