Node.js async/await无法与fs.writeFile一起正常工作
我将回调传递给fs.writeStream,由于某种原因,在执行回调之前,首先调用它之后的任何任务Node.js async/await无法与fs.writeFile一起正常工作,node.js,asynchronous,async-await,fs,Node.js,Asynchronous,Async Await,Fs,我将回调传递给fs.writeStream,由于某种原因,在执行回调之前,首先调用它之后的任何任务 async function writeFile(file, callBack) { // awaiting this also doesn't work fs.writeFile(arg1, arg2, arg3, (error) => callBack(error)) } async function task() { let count = 0; cons
async function writeFile(file, callBack) {
// awaiting this also doesn't work
fs.writeFile(arg1, arg2, arg3, (error) => callBack(error))
}
async function task() {
let count = 0;
const callBack = (error) => {
if (error) {
count--;
} else {
count++;
}
}
for(const file of files) { // files.length = 1
await writeFile(file, callBack);
}
console.log(count) // Prints 0, should be 1. Why does this get called before the callback?
}
如果您导入了正确的fs库,即
fs/promises
,您的答案应该如下所示:
异步函数写入文件(文件){
等待fs.writeFile(文件);
}
异步函数任务(){
让计数=0;
常量回调=(错误)=>{
如果(错误){
计数--;
}否则{
计数++;
}
}
对于(文件的常量文件){//files.length=1
等待写入文件(文件);
}
console.log(count)//打印0,应该是1。为什么在回调之前调用它?
}
您缺少实际等待fsPromises.writeFile的异步结果所需的wait
,您可以在此处看到:
此外,如果您使用的是基于承诺的fs,那么您将不会也不需要回调(ftfy)
如果仍要计数,请按以下方式进行:
异步函数写入文件(文件){
等待fs.writeFile(文件);
}
异步函数任务(){
让计数=0;
对于(文件的常量文件){//files.length=1
试一试{
等待写入文件(文件);
count++;//首先,你调用它是错误的。如果你想等待一个异步函数,你必须用wait
await yourFunction(...);
与async
async yourFunction();
其次,很明显,您将async
函数和回调函数混合在一起
async function yourFunction() {
anotherFunction((error, data) => {
...
});
}
实际上,您正在返回一个Promise
,该函数将立即解析。async
函数不等待任何基于回调函数的回调
第三,您使用的不是writeFile(file,callBack)
函数的file
参数,而是三个完全未定义的参数arg1、arg2、arg3
对于您当前的问题,有两种可能性
导入fs
模块的promise函数并正确使用它们(从节点v10开始提供)
您将导入fs模块的经典回调形式,并将函数包装成承诺
const fs = require("fs");
async function writeFile(filename, data, errorHandler) {
return new Promise((resolve, reject) => {
fs.writeFile(filename, data, (e) => {
if (e) {
errorHandler(e);
// if you want to continue and adjust the count
// even if the writeFile failed
// you don't need the reject here
return reject(e);
}
resolve();
});
});
}
相当过时,但是的。修复了.tyasync
在发布此内容时出现的打字错误-应该是wait
。我也尝试了waitfs.writeFile
但不起作用。将尝试您的建议!什么“不起作用”使用等待fs.writeFile
?是否有错误消息?是否导入了fs模块的承诺表单?
const fs = require("fs");
async function writeFile(filename, data, errorHandler) {
return new Promise((resolve, reject) => {
fs.writeFile(filename, data, (e) => {
if (e) {
errorHandler(e);
// if you want to continue and adjust the count
// even if the writeFile failed
// you don't need the reject here
return reject(e);
}
resolve();
});
});
}