How does the Node.js event loop work?

前端 未结 2 721
面向向阳花
面向向阳花 2021-02-03 12:56

After playing with Node.js and reading about async i/o & evented programming a lot I\'m left with some question marks.

Consider the following (pseudo) code:

相关标签:
2条回答
  • 2021-02-03 13:20

    Run parrallel async code pattern:

    To 'Wait for result from both async functions' you can do: in both async calls callbacks check both result and if all ready, call your DoSomethingWithTwoDependantResults.

    In your example you probably need to execute queries sequentially:

    query(sql1, function(sqlres1) {
        query(sql2, function(sqlres2) {
            writeResultUsingDataFrom(sqlres1, sqlres2);
        }
    });
    

    your original code, modified to execute two queries in parallel:

    function writeReply(res, template, username, event_name)
    {
        var body = renderView(username, event_name, template);
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.write(body);
        res.end();
    } 
    
    function onRequest(request, response)
    {
        // some non-blocking db query
        query('SELECT name FROM users WHERE key=req.params['key']', function (err, results, fields) {
            if (err) {
                throw err;
            }
            username = results[0];
            if (username && event_name)
                writeReply(res, template, username, event_name);
        });
    
        // some non-blocking db query
        query('SELECT name FROM events WHERE key=req.params['key']', function (err, results, fields) {
            if (err) {
                throw err;
            }
            event_name = results[0];
            if (username && event_name)
                writeReply(res, template, username, event_name);
    
        });
    };
    
    0 讨论(0)
  • 2021-02-03 13:23

    Have you seen this? I'm still getting the hang of it all and I can't answer your question in detail, but basically you're right about the thread-pool... Ryan explains quite a lot in the video.

    EDIT: And this one from about a year later, when he goes into more detail.

    0 讨论(0)
提交回复
热议问题