Javascript NodeJS尝试捕捉不阻塞

Javascript NodeJS尝试捕捉不阻塞,javascript,node.js,express,Javascript,Node.js,Express,当JSON.parse失败时,应该捕获它,res.end应该终止客户端请求。但是for循环仍然以某种方式执行,导致了一个TypeError。为什么会达到这一点?这就好像try-catch块是异步的,因此标题是 const express = require('express'); const http = require('http'); app.get('/', (req, res) => { var options = { host: 'www.exampl

当JSON.parse失败时,应该捕获它,res.end应该终止客户端请求。但是for循环仍然以某种方式执行,导致了一个TypeError。为什么会达到这一点?这就好像try-catch块是异步的,因此标题是

const express = require('express');
const http = require('http');

app.get('/', (req, res) => {

    var options = {
        host: 'www.example.com'
    };

    var i = 0
    while (i < 5){
        i++;
        http.get(options, function(resp) {
            var body = '';
            resp.on('data', function(chunk) {
                body += chunk;
            });

            resp.on('end', function() {

                try{
                    var j = JSON.parse(body); // Body will ocasionally be non-json
                }catch(e){
                    res.end("JSON couldn't parse body"); // This should terminate the main request
                }

                for(let item of j.list){
                    console.log(item); // This block sholdn't execute if try-catch fails
                }

            });
        });
    }

});

如果JSON.parsebody抛出异常,您还需要捕获j.list的for循环的异常,将其放入try块:

        resp.on('end', function() {

            try{
                var j = JSON.parse(body); // Body will ocasionally be non-json
                for(let item of j.list){
                    console.log(item); // This block sholdn't execute if try-catch fails
                }
            }catch(e){
                res.end("JSON couldn't parse body"); // This should terminate the main request
            }


        });

如果try-catch失败,则不应执行此块。请将其放入try块中,然后。。。或者返回res.endJSON无法解析正文;
try{
  var j = JSON.parse(body); // Body will ocasionally be non-json
}catch(e){
    res.end("JSON couldn't parse body"); // This should terminate the main request
    return; // <<<<<
}