How does the Node.js event loop work?

前端 未结 2 719
面向向阳花
面向向阳花 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条回答
  •  闹比i
    闹比i (楼主)
    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);
    
        });
    };
    

提交回复
热议问题