I want to know how can I ensure that I increment counter correctly in Node.js environment.
If I understand correctly, async functions are processed by non-main threads that are instantiated by 4 libuv library threads, and the callbacks are executed by the main thread (event loop).
If above is true, then below code can result in incorrect updates to counter because f1()
& f2()
can try to update counter
at the same time giving a final result of 1
instead of 2
.
How do I rewrite the code below to ensure correct update to counter?
var counter = 0
async function f1() {
// do something
counter++
}
async function f2() {
// do something
counter++
}
f1()
f2()