我一直在读node初学者 我看到了下面两段代码。

第一个问题:

    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('Hello world')。

第一个应该是同步代码。 第二种是异步代码。

这两件作品之间的区别对我来说很模糊。输出是什么?

在谷歌上搜索异步编程也没什么用。


当前回答

同步函数是阻塞的,而异步函数不是。在同步函数中,语句在运行下一个语句之前完成。在这种情况下,程序完全按照语句的顺序求值,如果其中一条语句花费了很长时间,则程序的执行将暂停。

Asynchronous functions usually accept a callback as a parameter and execution continue on the next line immediately after the asynchronous function is invoked. The callback is only invoked when the asynchronous operation is complete and the call stack is empty. Heavy duty operations such as loading data from a web server or querying a database should be done asynchronously so that the main thread can continue executing other operations instead of blocking until that long operation to complete (in the case of browsers, the UI will freeze).

最初发布在Github:链接

其他回答

如果你在两个例子中都加上一行,这将变得更清楚:

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

第二点:

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

尝试运行这些程序,您将注意到第一个(同步)示例的结果。长度将在'Hello World'行之前打印出来。 在第二个(异步)示例中,结果。length将(很可能)打印在"Hello World"行之后。

这是因为在第二个例子中,数据库。查询在后台异步运行,脚本直接继续“Hello World”。console.log(result.length)只在数据库查询完成时执行。

这两种方法的区别如下:

同步方式: 它等待每个操作完成,之后只执行下一个操作。 如有查询: console.log()命令直到&才会执行,除非查询已经完成从Database中获取所有结果。

异步方式: 它从不等待每个操作完成,而是只在第一个GO中执行所有操作。一旦结果可用,就会处理每个操作的结果。 如有查询: console.log()命令将在Database.Query()方法之后很快执行。而数据库查询在后台运行,并在检索数据完成后加载结果。

用例

如果你的操作不是很繁重,比如从DB中查询大量数据,那么就使用同步方式,否则就使用异步方式。 在异步方式中,你可以向用户显示一些进度指示器,而在后台你可以继续你的繁重工作。这是GUI应用程序的理想场景。

JS中的异步编程:

同步

停止执行进一步的代码,直到完成此操作。 因为它停止了进一步的执行,同步代码被称为“阻塞”。阻塞是指没有其他代码将被执行。

异步

它的执行被延迟到事件循环中,这是JS虚拟机中的一个构造,它执行异步函数(在同步函数堆栈为空之后)。 异步代码之所以称为非阻塞代码,是因为它不会阻塞进一步的代码运行。

例子:

//该函数是同步的 函数日志(参数){ console.log (arg) } 日志(1); //该函数是异步的 setTimeout(() => { console.log (2) }, 0); 日志(3)

示例记录1、3、2。 2被记录在最后,因为它在一个异步函数中,该函数在堆栈为空后执行。

主要的区别是异步编程,否则你不会停止执行。当“请求”被发出时,您可以继续执行其他代码。

同步函数是阻塞的,而异步函数不是。在同步函数中,语句在运行下一个语句之前完成。在这种情况下,程序完全按照语句的顺序求值,如果其中一条语句花费了很长时间,则程序的执行将暂停。

Asynchronous functions usually accept a callback as a parameter and execution continue on the next line immediately after the asynchronous function is invoked. The callback is only invoked when the asynchronous operation is complete and the call stack is empty. Heavy duty operations such as loading data from a web server or querying a database should be done asynchronously so that the main thread can continue executing other operations instead of blocking until that long operation to complete (in the case of browsers, the UI will freeze).

最初发布在Github:链接