简体   繁体   English

同步vs异步Node.js

[英]Synchronous vs Asynchronous Nodejs

I was automating a webpage using the Mocha testing framework, and came upon the terms Synchronous and Asynchronous code. 我当时使用Mocha测试框架自动化网页,并想到了“同步和异步代码”一词。 I'm familiar with synchronous and asynchronous events when you send an HTTP request...but I've never heard of code being synchronous and asynchronous. 当您发送HTTP请求时,我对同步和异步事件很熟悉...但是我从未听说过代码是同步和异步的。 Anyone care to explain...I saw on previous questions that it has something to do with a callback, but even then I'm still pretty confused about the concept. 任何人都想解释一下...在以前的问题上,我看到它与回调有关,但是即使那样,我仍然对该概念感到困惑。

Below is a simplified version of my server code. 以下是我的服务器代码的简化版本。 I demonstrate both synchronous code (after you start doing an operation, no further operations are begun until it finishes) and asynchronous code (you start doing an operation, then continue to do other operations, and at some later point you "callback" or get a result from the first operation.) 我将演示同步代码(开始执行操作之后,直到其完成之前不会再进行其他操作)和异步代码(开始执行操作,然后继续执行其他操作,然后稍后再“回调”或获取)第一次操作的结果。)

This has some important consequences. 这有一些重要的后果。 Nearly every time you call an async function: 几乎每次您调用异步函数时:

  • the return value from your async function is useless, because the function will return immediately, although finding the result takes a long time. 异步函数的返回值是没有用的,因为该函数将立即返回 ,尽管查找结果需要很长时间。

  • you have to wait until the callback function is executed to have access to the result. 您必须等到执行回调函数才能访问结果。

  • lines of code following the call to the asynchronous function will execute BEFORE the asynchronous callback function runs. 异步函数调用之后的代码行将在异步回调函数运行之前执行。

As an example, the order of the console.logs in my code below will be: 例如,下面我的代码中console.logs的顺序为:

line 3 - before sync
line 8 - after sync, before async
line 16 - after async call, outside callback
line 14 - inside async call and callback



// synchronous operations execute immediately, subsequent code
// doesn't execute until the synchronous operation completes.
console.log('line 3 - before sync');
var app = require('express')();
var cfgFile = require('fs').readFileSync('./config.json');
var cfg = JSON.parse(cfgFile);
var server = require('http').createServer(app);
console.log('line 8 - after sync, before async');

// When you call an asynchronous function, something starts happening,
// and the callback function will be run later:
server.listen(cfg.port, function(){
  // Do things that need the http server to be started
  console.log('line 14 - inside async call and callback');
});
console.log('line 16 - after async call, outside callback');

Synchronous code will strictly be processed line by line whereas asynchronous code will continue to the next line while previous lines of code are still being processed. 严格来讲,同步代码将逐行处理,而异步代码将继续处理下一行,而前几行代码仍在处理中。

For asynchronous code, in the following snippet, you would expect World to be logged to console before Hello because the database query requires more of the computer's resources and therefore takes more time. 对于异步代码,在以下代码段中,您希望在Hello之前将World记录到控制台,因为数据库查询需要更多计算机资源,因此需要更多时间。 console.log('World') would finish executing before the query. console.log('World')将在查询之前完成执行。

var Person = mongoose.model('Person', personSchema);

Person.findOne({ 'name.last': 'Ghost' }, function(err, person) {
  if(err) 
    throw err;
  else
    console.log('Hello');
});

console.log('World');

In synchronous code, Hello will be logged before World because the query finishes executing before any following lines are executed. 在同步代码中, Hello将在World之前记录,因为查询将在执行以下任何行之前完成执行。

Synchronous Code basically means the lines of code are executed in the order they are written. 同步代码基本上意味着代码行按它们被写入的顺序执行。 Synchronous events will immediately execute an associated callback like it would a direct function call so the end result is the same. 同步事件将立即执行关联的回调,就像直接调用函数一样,因此最终结果相同。

In general, Asynchronous Code is executed separately and concurrently from the calling code. 通常, 异步代码与调用代码分开并发执行。 eg Calling setTimeout will immediately return and execute the next expression but it will have started an action that at some point in the future it will fire an Asynchronous Event that calls the specified callback. 例如,调用setTimeout将立即返回并执行下一个表达式,但是它将启动一个动作,该动作在将来的某个时候将触发一个异步事件 ,该事件调用指定的回调。

The Mocha test framework supports both types of code and it supplies the done() callback for asynchronous code. Mocha测试框架支持两种类型的代码,并且为异步代码提供了done()回调。 done() is the callback that lets Mocha know when the test complete. done()是让Mocha知道测试何时完成的回调。

Asynchronous test code, From http://mochajs.org/ 异步测试代码,来自http://mochajs.org/

describe('User', function() {
  describe('#save()', function() {
    it('should save without error', function(done) { // done is a callback
      var user = new User('Luna');
      user.save(function(err) { // save is async db call that starts here, completes whenever
        if (err) throw err;
        done();
      });
    });
  });
});

Testing synchronous code doesn't require done(), the test code is expected to executed in order. 测试同步代码不需要done(),测试代码应按顺序执行。 So when the last expression is executed, the test is over. 因此,当执行最后一个表达式时,测试结束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM