-2

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?

pilchard
  • 12,414
  • 5
  • 11
  • 23
caeus
  • 3,084
  • 1
  • 22
  • 36
  • 3
    The answer to questions like that in the modern world is almost, almost always "no". – Pointy Dec 14 '22 at 21:52
  • 3
    `releaseResources` is invoked in both examples, but it runs immediately after the `fn()` call without waiting for it to complete in the first. – pilchard Dec 14 '22 at 22:02
  • 1
    the `releaseResources` is always executed. – Gabriele Petrioli Dec 14 '22 at 22:04
  • Thanks, I realized it too after making the question. Weird thing is that the released resources could still be used even though they were released almost immediately – caeus Dec 14 '22 at 22:14
  • It depends on what `fn()` is and whether it's creating a closure over the 'resources'. – pilchard Dec 14 '22 at 22:28

1 Answers1

3

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()
  }
Gradyn Wursten
  • 118
  • 2
  • 18