quickjs-emscripten icon indicating copy to clipboard operation
quickjs-emscripten copied to clipboard

How to catch error in async function?

Open ahaoboy opened this issue 1 year ago • 0 comments

If async function doesn't have await stmt, hasPendingJob return false throw Error in this function, I can't get the error msg

const asyncCode = `
async function main() {
    throw new Error('a')
  }
  
  main();
`

const syncCode = `
  function main() {
    throw new Error('a')
  }
  
  main();
`

const resultHd = vm.evalCode(code)

// asyncCode and syncCode both are false
vm.runtime.hasPendingJob()

import { getQuickJS } from "quickjs-emscripten"


async function exec(code) {
    const QuickJS = await getQuickJS()
    const vm = QuickJS.newContext()

    const world = vm.newString("world")
    vm.setProp(vm.global, "NAME", world)
    world.dispose()


    const resultHd = vm.evalCode(code)
    if (resultHd.error) {
        const error = vm.dump(
            resultHd.error
        )
        console.error('error1', error)
        return
    }

    console.error('vm.runtime.hasPendingJob()', vm.runtime.hasPendingJob())
    if (vm.runtime.hasPendingJob()) {
        const result = vm.unwrapResult(
            resultHd
        )
        const promise = result.consume((result) => vm.resolvePromise(result))
        vm.runtime.executePendingJobs()
        const asyncResult = await promise

        if (asyncResult.error) {
            const error = vm.dump(asyncResult.error)
            asyncResult.error.dispose()
            console.error('error2', error)
            return
        }
    }

}

async function main() {
    const asyncCode = `
    async function main() {
        throw new Error('a')
      }
      
      main();
  `

    const syncCode = `
      function main() {
        throw new Error('a')
      }
      
      main();
  `

    await exec(syncCode)
    await exec(asyncCode)

}

main()

ahaoboy avatar Aug 31 '22 09:08 ahaoboy