Today I came across a tweet:
https://twitter.com/BenLesh/status/1717272722193965511
I was shocked!
How is this possible? I have always thought that throw
is synchronous!
In case you don't know why this is weird:
synchronous code should run synchronously even in async function because the process of creating promise itself is synchronous (If everything is promise, what is the point of promise?)
proof:
console.log(123);
(async()=>{
try{
return await (async()=>{console.log(456)})()
}catch(e){
console.log({e},"error!")
}
})();
console.log(789)
but this obviously not the case with throw
!
console.log(123);
(async()=>{
try{
return await (async()=>{throw 456})()
}catch(e){
console.log({e},"error!")
}
})();
console.log(789)
async function
convert the suppose synchronous throw
into asynchronous throw
, what?!!
The closest explanation I can come up with is throw
is return
in disguise because return
behave in the similar way: async function change return
into returning promise. But still this doesn't explain everything and how can we make sense out of it.
update:
answer in these comments (read all replies)
TLDR, throw happens synchronously but is reported asynchronously
I am a bit puzzled why would someone expect that catch to be hit. Rejected promise passed on without await, so it is not handled in the
test
function of the original tweet.It works just the way it is written.