-1

I have several asynchronous functions running, and I'm wondering if it is possible to close a function that is running in the background. With its name for example ?

async function test(){
 await ...
 await ...
 await ...
}
/* CODE TO CLOSE the test function, something like : aclose("test"); ??? */
bob dylan
  • 989
  • 2
  • 10
  • 26

2 Answers2

0

There is not, because there is no need for one. An async function defined in JavaScript does not run in the background; it runs concurrently, but not in parallel. Whenever JS code is actually executing, it is in the foreground.

If you want other code to be able to stop the function from completing, you need to write your async function to cooperate. You could, for example, set up a shared closure variable that external code can set, and then have your async function check that variable after every await statement to see if it should return early.

Logan R. Kearsley
  • 682
  • 1
  • 5
  • 19
0

I'm assuming that by "close" you mean "cancel" the asynchronous pipeline started by the function. You have to track cancellation inside the async function using something like the Cancellation Token pattern. While JavaScript does not have a construct for this built-in, you can use a package such as cancellationtoken.

You can call the token's cancel function from anywhere, and check regularly inside the async function to see if it has been cancelled. If it has, you can simply return out. If not, you continue your work.

Arcanox
  • 1,420
  • 11
  • 20