NodeJ-一起编写异步和非异步函数

时间:2020-09-06 23:17:00

标签: node.js function promise async-await undefined

这是我的模块,其中x返回为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)

checkSystemData()不能由其作者制作,async是更大模块的一部分。我如何重构它以将x接收为{ check: false, manufacturer: sd.manufacturer }

1 个答案:

答案 0 :(得分:0)

您需要从checkSystemData()返回一些内容

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

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

然后您就可以使用

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

let x = await checkSystemData()