When using await on a function with callback, such as fs.writeFile, await doesn't wait for the code inside the callback to execute. For example:
const fs = require("fs")
async function test() {
for (let i = 0; i < 3; i++) {
console.log(`processing ${i}`)
const fileName = `${i}.json`
await fs.writeFile(fileName, JSON.stringify(i), err => {
if (err) throw err
console.log(`file ${i} is written`)
})
console.log(`${i} is done.`)
}
}
test()
The above code produces:
processing 0
0 is done.
processing 1
1 is done.
processing 2
2 is done.
file 1 is written
file 0 is written
file 2 is written
instead of:
processing 0
file 0 is written
0 is done.
processing 1
file 1 is written
1 is done.
processing 2
file 2 is written
2 is done.
Could anyone please explain why await fails to let it finish writing the file before continuing?