是什么同步和异步编程之间的差(在的node.js) [英] What is the difference between synchronous and asynchronous programming (in node.js)

查看:137
本文介绍了是什么同步和异步编程之间的差(在的node.js)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读 nodebeginner
而且我碰到code以下两个部分。

I've been reading nodebeginner And I came across the following two pieces of code.

第一个:

    var result = database.query("SELECT * FROM hugetable");
    console.log("Hello World");

第二个:

    database.query("SELECT * FROM hugetable", function(rows) {
       var result = rows;
    });
    console.log("Hello World");

我得到他们应该做的,他们查询数据库检索答案查询。然后的console.log(世界,你好')

第一个是所谓同步code。
而第二个是异步code。

The first one is supposedly synchronous code. And the second one is asynchronous code.

两片之间的区别是很模糊了我。将输出的是什么呢?

The difference between the two pieces is very vague to me. What would the output be?

在谷歌搜索异步编程也帮不了我。

Googling on asynchronous programming didn't help me either.

推荐答案

不同的是,在第一个例子中,程序将在第一线阻塞。下一行(的console.log )将不得不等待。

The difference is that in the first example, the program will block in the first line. The next line (console.log) will have to wait.

在第二个例子中,的console.log 将正在处理的查询执行。也就是说,查询会在后台进行处理,而你的程序是做其他事情,而一旦查询数据准备好了,你会做你想做的事情不管。

In the second example, the console.log will be executed WHILE the query is being processed. That is, the query will be processed in the background, while your program is doing other things, and once the query data is ready, you will do whatever you want with it.

所以,概括地说:

第一个例子将阻塞,而第二不会

The first example will block, while the second wont.

下面的两个实施例中的输出:

The output of the following two examples:

//example 1
var result = database.query("SELECT * FROM hugetable");
console.log("query finished");
console.log("Next line");


//example 2
database.query("SELECT * FROM hugetable", function(result) {
    console.log("query finished");
});
console.log("Next line");

是:


  1. 查询完成结果
    下一行

  2. 下一行结果
    查询完成

  1. query finished
    Next line
  2. Next line
    query finished

注意的结果
虽然节点本身的单线程,还有一些可以并行运行某些任务。例如,发生在不同的进程文件系统操作。结果
这就是为什么节点可以做异步操作:一个线程执行文件系统操作,而主节点线程执行保持你的JavaScript code结果。
你可以阅读更多关于这个在这里:单线程非阻塞IO模型如何在Node.js的

Note
While Node itself is single threaded, there are some task that can run in parallel. For example, File System operations occur in a different process.
That's why Node can do async operations: one thread is doing file system operations, while the main Node thread keeps executing your javascript code.
You can read more about this here: How the single threaded non blocking IO model works in Node.js

这篇关于是什么同步和异步编程之间的差(在的node.js)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆