在以下節點函式中,它回傳一個空陣列。不知道它為什么這樣做。這可能是一個異步等待的問題嗎?希望得到任何幫助。謝謝你
。const folderPath = '/public/home.html'/span>
function getCircuitAndFuse(folderPath){
//List containing circuit name with its fuse。
let temporaryList = [];
let finalCircuitAndFuseList = [].
fs.readFile(__dirname folderPath, (error, data)=> {
if(錯誤){
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(" "/span>))
})
finalCircuitAndFuseList = [...new Set(temporaryList)] 。
}
})
return finalCircuitAndFuseList;
}
let getInfo = getCircuitAndFuse(folderPath)
//回傳空陣列。
console.log(getInfo)
***Server code****
const server = http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/plain'})
res.end()
}).listen(port, ()=>/span>{
console.log(`Server listening on port ${port}。按Ctrl-C終止...`)
})
uj5u.com熱心網友回復:
getCircuitAndFuse必須像這樣回傳Promise:
function getCircuitAndFuse(folderPath) {
return new Promise((resolve, reject) => /span>{
//List containing circuit name with its fuse[/span]。
let temporaryList = [];
fs.readFile(__dirname folderPath, (error, data) => {
if (error) {
console.log(`Unable to read file: ${error}`)。)
} else {
var $ = cheerio.load(資料)。
$('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) => {
//對`getInfo`做一些事情。
});
uj5u.com熱心網友回復:
Faruk的答案的另一個選擇是直接使用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(錯誤)。
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/332240.html
標籤:
