【问题标题】:fs.unlink asyncronous node.jsfs.unlink 异步 node.js
【发布时间】:2021-09-03 14:04:28
【问题描述】:

移除 async 并 await 代码正常工作,如果 unlink 是 async 函数,出现此错误是什么问题?在这种情况下,由于取消链接仅删除文件函数并返回 null,因此在 Promise 中是否真的必须有一个 resolve(...)?

c:\Users\Flavio\Documents\Coding\projects-my\study-content\study-luiz-miranda\node\file-system\unlink.js:7
  let deletedFile = await fs.unlink(path.join(dir, file));
                    ^^^^^

SyntaxError: await is only valid in async function
    at wrapSafe (internal/modules/cjs/loader.js:984:16)
    at Module._compile (internal/modules/cjs/loader.js:1032:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
    at Module.load (internal/modules/cjs/loader.js:933:32)
    at Function.Module._load (internal/modules/cjs/loader.js:774:14)
    at Module.require (internal/modules/cjs/loader.js:957:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (c:\Users\Flavio\Documents\Coding\projects-my\study-content\study-luiz-miranda\node\app.js:1:24)
    at Module._compile (internal/modules/cjs/loader.js:1068:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
const fs = require('fs').promises;
const path = require('path');

exports.deleteFile = async (dir, file) => new Promise((resolve, reject) => { 
  let deletedFile = await fs.unlink(path.join(dir, file), (err) => {
    if (err) return reject(err);
  });
  resolve(console.log('Deleted'))
})

【问题讨论】:

  • 承诺取消链接是没有意义的。因为你使用了 fs.promises,所以它已经返回了一个 Promise。

标签: javascript node.js es6-promise async.js


【解决方案1】:

您正在使用 fs.promises.unlink,它不接受回调。相反,它返回一个您可以选择等待的承诺。您也不需要使用 new Promise() - new Promise() 旨在将回调 API 转换为基于承诺的 API,但您已经在使用基于承诺的 API。

所以,这实际上就是你想要做的所有事情:

const fs = require('fs').promises;
const path = require('path');

exports.deleteFile = async (dir, file) => {
  await fs.unlink(path.join(dir, file));
  console.log('Deleted')
}

要回答有关天气的问题,您必须在使用new Promise() 时使用resolve(),答案是,否则您的承诺将永远无法解决,等待它的任何事情都会等待永远。但是,如果您没有要提供的值,则不必为 resolve() 提供任何特定值。

【讨论】:

    【解决方案2】:

    你应该更好地理解承诺

    const fs = require('fs').promises;
    const path = require('path');
    
    exports.deleteFile = async (dir, file) => { 
        await fs.unlink(path.join(dir, file))      
        console.log('Deleted')
    }
    

    async/await 函数总是返回一个 promise。

    【讨论】:

    • 是的,你说的很好,但这也取决于你想做什么。我不想展示解决方案,我希望他了解承诺,除了他不应该使用回调。 ☺
    • 准备好了,已经编辑好了。 @jfriend00 感谢您的 cmets。
    猜你喜欢
    • 2013-05-11
    • 2015-02-23
    • 2011-07-05
    • 1970-01-01
    • 2015-05-16
    • 2016-04-29
    • 2017-03-20
    • 1970-01-01
    • 2023-03-04
    相关资源
    最近更新 更多