我看过很多promise教程和callback教程,我想我只是一无所获。我下面的代码读取目录中的所有文件并处理这些文件。当结束时,我需要它调用writeToFile()..但是writeToFile在处理完成之前会得到调用。我希望这篇文章能最终结束我的困惑。谢谢。下面的代码:
function go(callbackFunction){
var fs = require('fs');
fs.readdir('./filesToProcess', (err, files) => {
for (var i = 0; i < files.length; i++) {
//console.log("run the process on : " + files[i]);
console.log("Processing: " + files[i] + "\n");
processFile('./filesToProcess/' + files[i]);
};
});
callbackFunction();
}
go(writeToFile);
您必须等待功能完成,让我解释一下承诺
const foo = async () =>{ /* some function that takes time */}
// If I call foo like this "as you did inside the go function"
foo()
console.log("After foo")
//The console.log will print before the foo execute because you didn't wait for it
//The correct way is
await foo()
console.log("After foo")
//or
foo().then(() => console.log("After foo") )
要进一步了解如何使用诺言Here
您可以尝试异步/等待
Async function go(){...
await fs.readdir(...
}
或者如果fs.readdir返回一个诺言,您可以这样做:
function go(callback){
fs.readdir('./filesToProcess', (err, files) => {
for (var i = 0; i < files.length; i++) {
//console.log("run the process on : " + files[i]);
console.log("Processing: " + files[i] + "\n");
processFile('./filesToProcess/' + files[i]);
};
}).then(callback (){})
您要做的就是将callbackFunction移到传递给readdir的回调中,这样,您将确保仅在处理完成后才执行它。
function go(callbackFunction){
var fs = require('fs');
fs.readdir('./filesToProcess', (err, files) => {
for (var i = 0; i < files.length; i++) {
//console.log("run the process on : " + files[i]);
console.log("Processing: " + files[i] + "\n");
processFile('./filesToProcess/' + files[i]);
};
**callbackFunction();**
});
}
go(writeToFile);