#javascript #node.js
Вопрос:
В следующей функции узла он возвращает пустой массив. Не знаю, зачем он это делает. Может ли это быть проблемой асинхронного ожидания? Буду признателен за любую помощь. Спасибо
const folderPath = '/public/home.html'
function getCircuitAndFuse(folderPath){
//List containing circuit name with its fuse
let temporaryList = [];
let finalCircuitAndFuseList = []
fs.readFile(__dirname folderPath, (error, data)=>{
if(error){
console.log(`Unable to read file: ${error}`)
}else{
var $ = cheerio.load(data)
$('img').each(function(index, element){
let getClassAtr = element.attribs.class
temporaryList.push(getClassAtr.slice(0, getClassAtr.lastIndexOf(" ")))
})
finalCircuitAndFuseList = [...new Set(temporaryList)]
}
})
return finalCircuitAndFuseList;
}
let getInfo = getCircuitAndFuse(folderPath)
// Returning empty array
console.log(getInfo)
***Server code****
const server = http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/plain'})
res.end()
}).listen(port, ()=>{
console.log(`Server listening on port ${port}. Press Ctrl-C to terminate...`)
})
Комментарии:
1. Ваша функция возвращается до завершения fs.ReadFile. Поскольку этот метод асинхронен, Node выполняет его и немедленно переходит к нижней части функции и каждый раз возвращает вам пустой массив.
2. Я бы сказал «да». ваша консоль. журнал запускается до завершения функции. у вас есть асинхронный вызов (ReadFile), который необходимо завершить, прежде чем вы попытаетесь получить доступ к возвращаемому значению.
Ответ №1:
getCircuitAndFuse
должен вернуться Promise
вот так:
function getCircuitAndFuse(folderPath) {
return new Promise((resolve, reject) => {
//List containing circuit name with its fuse
let temporaryList = [];
fs.readFile(__dirname folderPath, (error, data) => {
if (error) {
console.log(`Unable to read file: ${error}`);
} else {
var $ = cheerio.load(data);
$('img').each(function (index, element) {
let getClassAtr = element.attribs.class;
temporaryList.push(
getClassAtr.slice(0, getClassAtr.lastIndexOf(' '))
);
});
resolve([...new Set(temporaryList)]);
}
});
});
}
getCircuitAndFuse(folderPath).then((getInfo) => {
// do something with `getInfo`
});
Ответ №2:
Другой альтернативой ответу Фарука было бы просто использовать fs.readFileSync
вместо того, чтобы оборачивать свою функцию обещанием и требовать некоторой дополнительной церемонии. Использование fs.readFileSync
гарантирует, что ваша функция не вернется преждевременно.
Вот ваш код, переписанный с учетом этого:
function getCircuitAndFuse(folderPath) {
try {
let temporaryList = [];
const data = fs.readFileSync(__dirname folderPath);
const $ = cheerio.load(data);
$("img").each(function (index, element) {
let getClassAtr = element.attribs.class;
temporaryList.push(getClassAtr.slice(0, getClassAtr.lastIndexOf(" ")));
});
return [...new Set(temporaryList)];
} catch (error) {
console.log(error);
}
}