简体   繁体   English

为什么等待不等待回调?

[英]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.在带有回调的 function 上使用 await 时,例如 fs.writeFile,await 不会等待回调中的代码执行。 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?谁能解释为什么 await 在继续之前无法让它完成写入文件?

This is because writeFile doesn't return a Promise and await waits for a Promise resolution before suspending the execution.这是因为writeFile不返回Promise并且await在暂停执行之前等待 Promise 分辨率。 You can either upgrade to the latest version of writeFile or write a function which returns a promise :您可以升级到最新版本的writeFile或编写返回 promise 的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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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