【发布时间】: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