NodeJS return 没有停止整个功能
NodeJS return not stopping the entire function
我有函数 enter,它在最里面的读取文件中包含两个 fs.readFile 函数 我正在检查一个 txt 文件是否包含某个关键字,如果确实如此,它应该停止整个 enter 函数。
她是 enter 函数的样子:
async function enter(email, firstName, lastName){
fs.readFile(fileName, function(err, data){
parsedData = JSON.parse(data);
email = parsedData.email;
fs.readFile('./anotherfile.txt', function (err, data) {
if (err) throw err;
if(data.includes(email)){
console.log('Stopping function');
return;
}
});
});
console.log('Continuing with function');
}
问题是当 anotherfile.txt 包含关键字时,它不会停止整个函数,它会继续并记录,"Continuing with function" 如上面的代码所示。
如有任何帮助,我们将不胜感激!
fs promises are available Node v11.0.0
or You can can convert like this const readFile = util.promisify(fs.readFile);
const fsp = require('fs').promises;
async function enter(email, firstName, lastName) {
try {
let data = await fsp.readFile(fileName)
let parsedData = JSON.parse(data);
let email = parsedData.email;
data = await fsp.readFile('./anotherfile.txt')
if (data.includes(email)) {
console.log('Stopping function');
return;
}
console.log('Continuing with function');
} catch (err) {
throw err
}
}
这是因为两件事。
您正在使用异步文件读取,即调用此readFile 时代码流不会停止。相反,该程序将继续以正常方式执行。当文件读取操作完成时,您提供的回调函数将被调用,并返回相应的错误或数据。
return语句在回调函数中,因此它只会影响那个函数。
你在处理异步函数的时候需要用到await
。查一下 here
我有函数 enter,它在最里面的读取文件中包含两个 fs.readFile 函数 我正在检查一个 txt 文件是否包含某个关键字,如果确实如此,它应该停止整个 enter 函数。
她是 enter 函数的样子:
async function enter(email, firstName, lastName){
fs.readFile(fileName, function(err, data){
parsedData = JSON.parse(data);
email = parsedData.email;
fs.readFile('./anotherfile.txt', function (err, data) {
if (err) throw err;
if(data.includes(email)){
console.log('Stopping function');
return;
}
});
});
console.log('Continuing with function');
}
问题是当 anotherfile.txt 包含关键字时,它不会停止整个函数,它会继续并记录,"Continuing with function" 如上面的代码所示。
如有任何帮助,我们将不胜感激!
fs promises are available Node v11.0.0 or You can can convert like this
const readFile = util.promisify(fs.readFile);
const fsp = require('fs').promises;
async function enter(email, firstName, lastName) {
try {
let data = await fsp.readFile(fileName)
let parsedData = JSON.parse(data);
let email = parsedData.email;
data = await fsp.readFile('./anotherfile.txt')
if (data.includes(email)) {
console.log('Stopping function');
return;
}
console.log('Continuing with function');
} catch (err) {
throw err
}
}
这是因为两件事。
您正在使用异步文件读取,即调用此readFile 时代码流不会停止。相反,该程序将继续以正常方式执行。当文件读取操作完成时,您提供的回调函数将被调用,并返回相应的错误或数据。
return语句在回调函数中,因此它只会影响那个函数。
你在处理异步函数的时候需要用到await
。查一下 here