When does the '.finally' block run in async function?

469 Views Asked by At

So I have a function that encloses an async computation to ensure at the end of the computation, something happens (like releasing certain resources).

so the function goes like

const withinScope = async(fn)=>{
  try{
    return fn()
  }finally{
    await releaseResources()
  }
}

Yet, the releaseResources method is never invoked!

Now, if I rewrite it like this:

const withinScope = async(fn)=>{
  try{
    const result = await fn()
    return result
  }finally{
    await releaseResources()
  }
}

it works... I kind of get why, but I'd say that's definitely a bug. But is it? or is it the intended behaviour?

1

There are 1 best solutions below

0
Gradyn Wursten On

Nope. This is behaving as expected. If you do not await an async method, the program will not wait for it to complete before continuing. Try

const withinScope = async(fn)=>{
  try{
    return await fn()
  }finally{
    await releaseResources()
  }