简体   繁体   中英

Why await doesn't wait for callback?

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?

This is because writeFile doesn't return a Promise and await waits for a Promise resolution before suspending the execution. You can either upgrade to the latest version of writeFile or write a function which returns a promise :

const fs = require("fs")
async function test() {
    for (let i = 0; i < 3; i++) {
        console.log(`processing ${i}`)
        const fileName = `${i}.json`
        await writeToFile(fileName, i);
        console.log(`${i} is done.`)
    }
}

function writeToFile(fileName, index) {
  return new Promise((resolve, reject) => {
     fs.writeFile(fileName, JSON.stringify(index), err => {
            if (err) {
              // denotes failure
              reject(err)
            }
            console.log(`file ${index} is written`);
            // denotes success
            resolve(true)
     })
  });
}

test()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM