Why is node.js asynchronous?

前端 未结 3 827
南方客
南方客 2020-11-28 20:12

Nobody has actually asked this (from all the \'suggestions\' I\'m getting and also from searching before I asked here).

So why is node.js asynchronous?

From

3条回答
  •  無奈伤痛
    2020-11-28 20:56

    Javascript does not compile into anything. It's "evaluated" at runtime, just like PHP & Ruby. Therefore it is a scripting language just like PHP/Ruby. (it's official name is actually ECMAScript).

    The 'model' that Node adheres to is a bit different than PHP/Ruby. Node.js uses an 'event loop' (the single thread) that has the one goal of taking network requests and handling them very quickly, and if for any reason it encounters an operation that takes a while (API request, database query -- basically anything involving I.O. (input/output)) it passes that off to a background 'worker' thread and goes off to do something else while the worker thread waits for the long task to complete. When that happens the main 'event loop' will take the results and continue deal with them.

    PHP/Ruby following a threading model. Essentially, for every incoming network request, the application server spins up an isloated thread or process to handle the request. This does not scale tremendously well and Node's approach is cited as one of its core strengths compared to this model.

    Asynchronous means stateless and that the connection is persistent whilst synchronous is the (almost) opposite.

    No. Synchronous instructions are completed in a natural order, from first to last. Asynchronous instructions mean that if a step in the flow of a program takes a relatively long time, the program will continue executing operations and simply return to this operation when complete.

    Could JavaScript be made into a synchronous language?

    Certain operations in JavaScript are synchronous. Others are asynchronous. For example:


    Blocking operations:

    for(var k = 0; k < 1; k = k - 1;){
      alert('this will quickly get annoying and the loop will block execution')
    alert('this is blocked and will never happen because the above loop is infinite');
    

    Asynchronous:

    jQuery.get('/foo', function (result) { alert('This will occur 2nd, asynchronously'); });
    alert('This will occur 1st. The above operation was skipped over and execution continued until the above operation completes.');
    

提交回复
热议问题