首页 > 解决方案 > fs.unlink 异步 node.js

问题描述

删除 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'))
})

标签: javascriptnode.jses6-promiseasync.js

解决方案


你应该更好地理解承诺

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。


推荐阅读