Evaling Async Function Definitions

I work on an IDE for Javascript that lets developers evaluate their code. In a modern Chrome console, I can run:

eval(`try{function foo3(){console.log("Hi")}} catch(err){console.log(err)}`)

and foo3 will be defined and called fine. I can also run:

eval(`async function foo4(){console.log("Hi")}`)

and foo4 will be defined and called fine. But when I run:

eval(`try{async function foo5(){console.log("Hi")}} catch(err) {console.log(err)}`)

I get no error, but foo5 is not defined. Note that the difference between example 1 and example 3 is just "async" before "function". I would like foo5 to be defined. Clues greatly appreciated.

6

1 Answer

Well, you could invert your code slightly, to include the try/catch block, within your async function to get it going.

eval(`async function foo5() {try {console.log("Hi")} catch (err) { console.log(err)}}`);

foo5();
4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest