Home > Software engineering >  Increment from asyncfunction is safe in Node.js?
Increment from asyncfunction is safe in Node.js?

Time:11-11

var i=0

async function a(){
 i       
}

a();

Can above code run safely? Even if Javascript is singlethread, especially during read modify write operation, another working thread can operate the same operation in async function.

CodePudding user response:

When an async function is invoked, it runs synchronously until an await happens inside the function. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function#description

Therefore, you can rely on i happening synchronously if it happens prior to any await statements in the function.

As your question acknowledges, Javascript is single threaded (unless you use web workers, but those are isolated from one another).

Use some kind of semaphore if you want to ensure that two different async methods do not adversely interleave with one another while modifying shared variables.

  • Related