-1

This is my existing code. I tried to get data with a child process spawned, and the promise resolves after the child is terminated

const {spawn} = require('child_process')

const getDataFromChildProcess = params => new Promise(resolve => {
  const child = spawn('script.js',[params])
  let data = null
  child.on('data',result => {
    data = result
  })
  child.on('exit',() => {
    resolve(data)
  })
})


getDataFromChildProcess('foo')
.then(result => {
  console.log(result)
})

How do I convert it into async-await style?

auphali
  • 139
  • 1
  • 8

1 Answers1

0

await will work inside async function. For your example - you will need to wrap your operation inside a async fn.

With that said you When you wrap something with a fn, you will need to execute that fn too. For that I used IIFE in my example- https://developer.mozilla.org/en-US/docs/Glossary/IIFE

refer - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function#Description

const {spawn} = require('child_process')

const getDataFromChildProcess = params => new Promise(resolve => {
  const child = spawn('script.js',[params])
  let data = null
  child.on('data',result => {
    data = result
  })
  child.on('exit',() => {
    resolve(data)
  })
})


(async() => {
 try{
    const result = await getDataFromChildProcess('foo')
    console.log(result)
  } catch(e) {
     console.log(e)
   }
})()
Satyam Pathak
  • 6,612
  • 3
  • 25
  • 52
  • You're missing the point, what I want to convert is the getDataFromChildProcess function, not how to execute that – auphali Aug 30 '19 at 22:22