由于node.js的异步性,不会发生更改

问题描述 投票:1回答:1

我是节点js的初学者,我正在用纯node.js做一个简单的项目。所以这是我的代码:

if(req.url ==="/"&&req.method==="POST"){
        let reqBody = "";
        req.on('data', chunk=>{
            reqBody += chunk.toString();
        });
        req.on("end", ()=>{
            reqBody = reqBody.split("&");
            for(let i=0; i<reqBody.length; i++){
                reqBody[i]=reqBody[i].split("=");
                reqBody[i] = reqBody[i][1];
                };
            //filter country    
            let countryFound;
            if(reqBody[1].length>0){
                    let countryList = "";
                    let countryVal = [];

                    countryListStream = fs.createReadStream("./public/country.list.json", "UTF-8");
                    countryListStream.on("data", countryChunk=>{
                        countryList+=countryChunk;
                        countryChunk = JSON.parse(countryChunk);
                        countryFound = countryChunk.filter(elem=> elem["name"].toLowerCase()==reqBody[1].toLowerCase());
                        if(countryFound.length!==0){
                            countryListStream.destroy();
                        };
                    });
                    countryListStream.on("end", ()=>{
                        countryFound = "Not Found"
                    });
            };
        });

    };

我的问题是在“过滤器国家/地区”注释之下:当我在“countryListStream”事件之外记录“countryFound”变量时,它会显示undefined.But当我在事件中记录它时,它会显示我想要的内容。我认为这是由于node.js是如何制作的,但我不知道如果它未定义则继续我的代码。我认为我需要包含一个等待变量更新的代码,然后运行其余的代码。我在if语句之后尝试了这个,并没有修复它:

if(countryFound!===undefined){
    console.log(countryFound);
}
node.js
1个回答
0
投票

从查看文档,调用countryStream.destroy()发出closeerror事件。因此,在close事件中添加处理程序是有意义的,您可以继续处理已分配给这些变量的值:

countryStream.on('close', () => {
    console.log(countryFound) // should not be undefined now
    // ...do something with your new values
});
© www.soinside.com 2019 - 2024. All rights reserved.