Node.js函数执行返回空数组,是否为async await异步相关问题
问题根因
你遇到的确实是异步执行逻辑导致的问题:
fs.readFile是Node.js内置的异步IO方法,传入的回调函数会在文件读取完成后才会被事件循环调度执行,而你的getCircuitAndFuse函数是同步执行的,会在调用fs.readFile之后立刻执行return finalCircuitAndFuseList,此时文件读取还没完成,回调里的数组赋值逻辑完全没运行,所以拿到的永远是空数组。
修复方案
方案1:改用async/await写法(推荐)
把异步读取逻辑包装成Promise,用await等待读取完成后再返回结果,代码修改如下:
const fs = require('fs/promises') // 改用Promise版本的fs模块 const cheerio = require('cheerio') const folderPath = '/public/home.html' async function getCircuitAndFuse(folderPath){ let temporaryList = []; try { // 等待文件读取完成 const data = await fs.readFile(__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(`Unable to read file: ${error}`) return [] } } // 调用异步函数需要用await或者.then获取结果 async function main() { let getInfo = await getCircuitAndFuse(folderPath) console.log(getInfo) } main()
方案2:保留回调写法
如果不想改Promise写法,可以把后续逻辑放到回调里执行:
const fs = require('fs') const cheerio = require('cheerio') const folderPath = '/public/home.html' function getCircuitAndFuse(folderPath, callback){ let temporaryList = []; fs.readFile(__dirname + folderPath, (error, data)=>{ if(error){ console.log(`Unable to read file: ${error}`) return callback([]) } const $ = cheerio.load(data) $('img').each(function(index, element){ let getClassAtr = element.attribs.class temporaryList.push(getClassAtr.slice(0, getClassAtr.lastIndexOf(" "))) }) const finalCircuitAndFuseList = [...new Set(temporaryList)] callback(finalCircuitAndFuseList) }) } getCircuitAndFuse(folderPath, (getInfo) => { console.log(getInfo) })
内容的提问来源于stack exchange,提问作者night_programmer
相关产品推荐
相关产品推荐

