[英]fs.unlink asyncronous node.js
當刪除 async 並等待代碼正常工作時,如果 unlink 是異步函數,出現此錯誤有什么問題? 在這種情況下,是否真的必須在 promise 中使用 resolve(...) ,因為 unlink 只刪除文件函數並返回 null?
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'))
})
你應該更好地理解承諾
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。
您正在使用 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()
,答案是yes ,否則您的承諾將永遠無法解決,任何等待它的東西都將永遠等待。 但是,如果您沒有要提供的值,則不必為resolve()
提供任何特定值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.