预期的行为:element.urls[j] == url
,因此触发了fs.readFile
。最终,代码到达fs.writeFile
并执行resolve(reply)
。
当前行为:代码按预期运行,直到fs.readFile
。 fs.readFile
开始同步运行,这意味着循环继续迭代,直到其中的代码块执行完毕。这导致我的循环过早结束,因此在fs.writeFile
完成并尝试执行resolve(reply)
时,它无济于事,因为诺言在循环结束时已被reject(reply)
拒绝了一旦到达数组末尾。
这是我的代码,请原谅console.log()s
。正在使用它们进行调试:
//Loop through monitor and access the "urls" key of each json
let i = 0;
for (let element of monitor) {
//Checks if the url is in the array
for (j = 0; j < element.urls.length; j++) {
if (element.urls[j] == url) {
console.log("yes the url is in the array");
//The URL is in the array
let item = monitor[i].product;
//Removes the URL from the array
monitor[i].urls.splice(j, 1);
//Updates config.json with the new data
console.log("removed the url from the arrauy");
//Code splits into two branches here for some reason
fs.readFile('./config.json', function (err, data) {
console.log("file is opened time to update");
var json = JSON.parse(data);
json.monitor = monitor;
fs.writeFile("./config.json", JSON.stringify(json), (err) => {
console.log("file updated");
let reply;
if (err) {
//There was an error trying to save the data
reply = [
{
"name": "An error occured trying to remove the url from array",
"value": `Error: ${err}`
}
];
//Exit
reject(reply);
return;
}
//Success
reply = [
{
"name": "Successfully removed url from array",
"value": `I will now stop monitoring the url supplied`
},
{
"name": "Item name",
"value": item
},
{
"name": "URL supplied",
"value": url
}
];
//Exit
resolve(reply);
return;
});
});
} else {
console.log("monitor length");
console.log(monitor.length-1);
console.log("value of i");
console.log(i);
console.log("length of elements urls");
console.log(element.urls.length-1);
console.log("value of j");
console.log(j);
//Check if this is the final iteration
if (i == monitor.length-1 && j == element.urls.length-1) {
console.log("ugh");
//This is the last iteration, the url supplied is not monitored by the bot
reply = [
{
"name": "The bot was never monitoring that URL",
"value": `The URL supplied isn't one that the bot currently monitors`
}
];
//Exit
reject(reply);
return;
}
}
}
console.log("incrementing");
//Increment i
i++;
};
以下是控制台输出,以便可以更好地可视化代码路径:
monitor length
1
value of i
0
length of elements urls
1
value of j
0
yes the url is in the array
removed the url from the arrauy
incrementing <----- Shows that the loop is incrementing already
monitor length <----- Start of the loop again
1
value of i
1
length of elements urls
0
value of j
0
ugh
????? <----- Comes from outside the function, shows that the function this loop is in has already ended
file is opened time to update <----- This comes from after fs.writeFile() is done opening the file
file updated <----- fs.writeFile() is done saving the file to disk
如您所见,第一个循环中断了,fs.readFile()
同步运行。
非常感谢您的投入。现在已经过去了几个小时了。
答案 0 :(得分:2)
fs.readFile()
是非阻塞的。这意味着您的for
循环会继续运行,同时会从您的循环中启动所有fs.readFile()
操作,并且它们同时都在运行中。然后,for
循环完成,有时稍后您的fs.readFile()
操作完成并调用其回调,并且它们可以按任何顺序完成。因此,在完成for
循环时,尚未调用任何fs.readFile()
完成回调,并且可以按任何顺序调用它们。那应该可以解释您在输出中看到的内容。
要使它们按顺序运行,最简单的方法是切换为使用promise和readFile的promise接口。从结构上看,如下所示:
// function needs to be async
async function someFunction() {
for (...) {
try {
let data = await fs.promises.readFile(...);
// do something with data
} catch(e) {
// handle error
}
}
// all files have been processed here
}
这将按顺序处理文件,暂停for
循环,直到完成每个连续的readFile()并依次运行异步操作。并且,在您的for
循环结束时,所有异步操作都将完成。
这使用await
在for
循环中对异步操作进行排序,因此必须将父函数标记为async
,并且它将返回一个承诺,指示何时完成所有操作。
答案 1 :(得分:0)
您可以在FileSystem模块中使用Sync方法。
阅读: https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options-> fs.readFileSync(path [,options])
写作: https://nodejs.org/api/fs.html#fs_fs_writefilesync_file_data_options-> fs.writeFileSync(file,data [,options])