【问题标题】:Why await doesn't wait for callback?为什么等待不等待回调?
【发布时间】:2022-01-21 01:10:34
【问题描述】:

在带有回调的函数(例如 fs.writeFile)上使用 await 时,await 不会等待回调中的代码执行。例如:

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()

以上代码产生:

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

代替:

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.

谁能解释一下为什么 await 不能让它在继续之前完成写入文件?

【问题讨论】:

标签: javascript async-await


【解决方案1】:

这是因为 writeFile 不返回 Promise 并且 await 在暂停执行之前等待 Promise 解决方案。您可以升级到最新版本的writeFile 或编写一个返回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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-12
    • 2021-05-29
    • 2021-06-30
    • 2021-08-02
    • 1970-01-01
    相关资源
    最近更新 更多