【问题标题】:fsPromises.writeFile callback not being called in Node v12.13.0在 Node v12.13.0 中未调用 fsPromises.writeFile 回调
【发布时间】:2020-02-23 08:58:21
【问题描述】:

无论出于何种原因,fs.promises 的回调都没有被调用,但文档没有提到它只有在出现错误时才会被调用,这就是我假设会发生的情况......

fsp.writeFile('test.txt', 'callback doesnt work', 'utf8', (error) => {
  console.log('callback is never called')
  if (error) console.error(error)
})

这在 Node 12.13.0 版本上发生(或不发生,哈哈)。

有人知道这是怎么回事吗?

【问题讨论】:

    标签: node.js promise filesystems fs


    【解决方案1】:

    fs.promises 版本的异步调用返回承诺。他们不接受回调。如果要使用回调,请使用常规的 fs 版本。

    您可以看到right here in the doc 没有为 API 的 fsPromises 版本传递回调的选项。

    你应该这样做:

    const fsp = require('fs').promises;
    
    fsp.writeFile('test.txt', 'promise works', 'utf8').then(() => {
        console.log("write successful");
    }).catch(err => {
        console.error(err);
    });
    

    或者,在async 函数中,您可以使用try/catchawait 而不是.then().catch()

    【讨论】:

    • 哦是的有道理,但是为什么documentation 说有回调?大声笑
    • 哦,是的,对不起,我绊倒了。如果你还不能告诉我节点对我来说是新的,哈哈
    • @PrimitiveNom - 您正在查看文档的 fs.writeFile() 部分,而不是 fs.promises.writeFile() portion of the doc
    • 是的,我在查看您编辑中的链接后注意到了这一点。无论如何,以下语法是否足以处理承诺? fsp.writeFile('test.txt', 'testing', error => error) 还是我应该以不同的方式处理承诺?承诺对我来说也是新的:/
    • @PrimitiveNom - 你看到这个How to chain and share prior results with promises了吗?请注意使用async/await 是多么简单。
    猜你喜欢
    • 1970-01-01
    • 2013-10-18
    • 2014-05-20
    • 2017-09-15
    • 2018-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多