caeus
caeus

Reputation: 3716

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

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?

Upvotes: -2

Views: 899

Answers (1)

Gradyn Wursten
Gradyn Wursten

Reputation: 158

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()
  }

Upvotes: 3

Related Questions