동기 프로그래밍과 비동기 프로그래밍의 차이점은 무엇입니까 (node.js에서)
나는 nodebeginner를 읽고 있었고 다음 두 가지 코드를 보았습니다 .
첫번째:
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')
.
첫 번째는 동기 코드 일 것입니다. 두 번째는 비동기 코드입니다.
두 조각의 차이점은 매우 모호합니다. 결과물은 무엇입니까?
비동기 프로그래밍에 대한 인터넷 검색도 도움이되지 않았습니다.
차이점은 첫 번째 예제 에서 프로그램이 첫 번째 라인에서 차단된다는 것입니다. 다음 줄 ( console.log
)을 기다려야합니다.
에서 두 번째 예 는이 console.log
질의가 처리되는 동안 실행된다. 즉, 쿼리는 백그라운드에서 처리되고 프로그램은 다른 작업을 수행하고 쿼리 데이터가 준비되면 원하는 작업을 수행합니다.
요컨대, 첫 번째 예는 차단되지만 두 번째 예는 차단되지 않습니다.
다음 두 가지 예의 출력 :
// Example 1 - Synchronous (blocks)
var result = database.query("SELECT * FROM hugetable");
console.log("Query finished");
console.log("Next line");
// Example 2 - Asynchronous (doesn't block)
database.query("SELECT * FROM hugetable", function(result) {
console.log("Query finished");
});
console.log("Next line");
될 것입니다 :
Query finished
Next line
Next line
Query finished
참고
노드 자체는 단일 스레드 이지만 병렬로 실행할 수있는 작업이 있습니다. 예를 들어 파일 시스템 작업은 다른 프로세스에서 발생합니다.
그렇기 때문에 Node가 비동기 작업을 수행 할 수 있습니다. 하나의 스레드는 파일 시스템 작업을 수행하고 기본 Node 스레드는 계속 자바 스크립트 코드를 실행합니다. Node와 같은 이벤트 중심 서버에서 파일 시스템 스레드는 완료, 실패 또는 진행과 같은 특정 이벤트 (예 : 데이터베이스 쿼리 결과 또는 오류와 같은 데이터)를 주 노드 스레드에 알립니다. 메시지)와 기본 노드 스레드가 해당 데이터로 수행 할 작업을 결정합니다.
여기에서 더 많은 것을 읽을 수 있습니다 : 단일 스레드 비 차단 IO 모델이 Node.js에서 작동하는 방법
이 두 가지 방법의 차이점은 다음과 같습니다.
동기 방식 : 각 작업이 완료 될 때까지 기다린 후 다음 작업 만 실행합니다. 쿼리의 경우 : console.log()
데이터베이스에서 모든 결과를 얻기 위해 쿼리 실행이 완료되지 않는 한 &가 될 때까지 명령이 실행되지 않습니다.
비동기 방식 : 각 작업이 완료 될 때까지 기다리지 않고 첫 번째 GO에서만 모든 작업을 실행합니다. 결과가 나오면 각 작업의 결과가 처리됩니다. 쿼리의 경우 : 메소드 console.log()
실행 후 명령이 곧 실행됩니다 Database.Query()
. 데이터베이스 쿼리는 백그라운드에서 실행되고 데이터 검색이 완료되면 결과를로드합니다.
사용 사례
DB에서 대량의 데이터를 쿼리하는 것과 같이 작업이 너무 많이 들리지 않으면 동기 방식으로 진행하고 그렇지 않으면 비동기 방식으로 진행하십시오.
비동기 방식으로 사용자에게 일부 진행 표시기를 표시 할 수 있으며 백그라운드에서 무거운 작업을 계속할 수 있습니다. 이것은 GUI 앱에 이상적인 시나리오입니다.
두 예제 모두에 줄을 추가하면 조금 더 명확 해집니다.
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");
이것을 실행하면 첫 번째 (동기식) 예제 인 result.length가 'Hello World'행 전에 인쇄됩니다. 두 번째 (비동기식) 예에서는 result.length가 "Hello World"행 뒤에 인쇄 될 가능성이 높습니다.
두 번째 예에서는 database.query
백그라운드에서 비동기식으로 실행되고 스크립트는 "Hello World"와 함께 계속 진행 되기 때문입니다 . 는 console.log(result.length)
데이터베이스 쿼리가 완료된 경우에만 실행됩니다.
먼저, 나는이 질문에 대답하는데 늦었다는 것을 알고 있습니다.
Before discussing synchronous and asynchronous, let us briefly look at how programs run.
In the synchronous case, each statement completes before the next statement is run. In this case the program is evaluated exactly in order of the statements.
This is how asynchronous works in JavaScript. There are two parts in the JavaScript engine, one part that looks at the code and enqueues operations and another that processes the queue. The queue processing happens in one thread, that is why only one operation can happen at a time.
When an asynchronous operation (like the second database query) is seen, the code is parsed and the operation is put in the queue, but in this case a callback is registered to be run when this operation completes. The queue may have many operations in it already. The operation at the front of the queue is processed and removed from the queue. Once the operation for the database query is processed, the request is sent to the database and when complete the callback will be executed on completion. At this time, the queue processor having "handled" the operation moves on the next operation - in this case
console.log("Hello World");
The database query is still being processed, but the console.log operation is at the front of the queue and gets processed. This being a synchronous operation gets executed right away resulting immediately in the output "Hello World". Some time later, the database operation completes, only then the callback registered with the query is called and processed, setting the value of the variable result to rows.
It is possible that one asynchronous operation will result in another asynchronous operation, this second operation will be put in the queue and when it comes to the front of the queue it will be processed. Calling the callback registered with an asynchronous operation is how JavaScript run time returns the outcome of the operation when it is done.
A simple method of knowing which JavaScript operation is asynchronous is to note if it requires a callback - the callback is the code that will get executed when the first operation is complete. In the two examples in the question, we can see only the second case has a callback, so it is the asynchronous operation of the two. It is not always the case because of the different styles of handling the outcome of an asynchronous operation.
To learn more, read about promises. Promises are another way in which the outcome of an asynchronous operation can be handled. The nice thing about promises is that the coding style feels more like synchronous code.
Many libraries like node 'fs', provide both synchronous and asynchronous styles for some operations. In cases where the operation does not take long and is not used a lot - as in the case of reading a config file - the synchronous style operation will result in code that is easier to read.
In the synchronous case, the console.log command is not executed until the SQL query has finished executing.
In the asynchronous case, the console.log command will be directly executed. The result of the query will then be stored by the "callback" function sometime afterwards.
The main difference is with asynchronous programming, you don't stop execution otherwise. You can continue executing other code while the 'request' is being made.
The function makes the second one asynchronous.
The first one forces the program to wait for each line to finish it's run before the next one can continue. The second one allows each line to run together (and independently) at once.
Languages and frameworks (js, node.js) that allow asynchronous or concurrency is great for things that require real time transmission (eg. chat, stock applications).
Sync Programming
Programming languages like C, C#, Java are sync programming, what so ever you write will be execute in order of your writing.
-GET DATA FROM SQL.
//Suppose fetching data take 500 msec
-PERFORM SOME OTHER FUNCTION.
//Performing some function other will take 100 msec, but execution of other
//task start only when fetching of sql data done (i.e some other function
//can execute only after first in process job finishes).
-TOTAL TIME OF EXECUTION IS ALWAYS GREATER THAN (500 + 100 + processing time)
msec
Async
NodeJs comes up with async feature, it's non-blocking in nature, suppose in any I/O task which is taking time (fetching, writing, reading), nodejs won't kept idle and wait for the task to be finish, it'll start executing next tasks in the queue, and whenever that time taking task completed it will notify using callback. Following example will help:
//Nodejs uses callback pattern to describe functions.
//Please read callback pattern to understand this example
//Suppose following function (I/O involved) took 500 msec
function timeConsumingFunction(params, callback){
//GET DATA FROM SQL
getDataFromSql(params, function(error, results){
if(error){
callback(error);
}
else{
callback(null, results);
}
})
}
//Suppose following function is non-blocking and took 100 msec
function someOtherTask(){
//some other task
console.log('Some Task 1');
console.log('Some Task 2');
}
console.log('Execution Start');
//Start With this function
timeConsumingFunction(params, function(error, results){
if(error){
console.log('Error')
}
else{
console.log('Successfull');
}
})
//As (suppose) timeConsumingFunction took 500 msec,
//As NodeJs is non-blocking, rather than remain idle for 500 msec, it will start
//execute following function immediately
someOtherTask();
In Short, Output is as:
Execution Start
//Roughly after 105 msec (5 msec it'll take in processing)
Some Task 1
Some Task 2
//Roughly After 510 msec
Error/Successful //depends on success and failure of DB function execution
Difference is clear where sync will definitely take more than 600 (500 + 100 + processing time) msec, async saves time.
'Programing' 카테고리의 다른 글
if [] (대괄호)의 "[: 너무 많은 인수"오류의 의미 (0) | 2020.05.19 |
---|---|
LaTeX에서 표 참조 (0) | 2020.05.19 |
Visual Studio Code에서 닫는 대괄호로 이동 (0) | 2020.05.19 |
ModelState.AddModelError-속성이 아닌 오류를 어떻게 추가합니까? (0) | 2020.05.19 |
`Optional.orElse ()`와`Optional.orElseGet ()`의 차이점 (0) | 2020.05.19 |