What is a blocking function?

1592 단어 삽입식
A function that stops script execution until it ends.
For example, if I had a function in my language that was used to write to a file, like so:
fwrite(file, "Contents");
print("Wrote to file!");

The  print  statement would only be executed once the file has been written to the disk. The whole program is halted on this instruction. This isn't noticeable for small enough writes, but imagine I had a huge blob to write to the file, one that took many seconds:
fwrite(file, blob);
print("Wrote to file!");

The  print  statement would only be executed after a few seconds of writting, and the whole program would be stopped for that time. In Node.js, this stuff is done asynchronously, using events and callbacks. Our example would become:
fwrite(file, blob, function() {
    print("Wrote to file!");
});
print("Do other stuff");

Where the third parameter is a function to be called once the file has been written. The  print statement located after the write function would be called immediately after, whether or not the file has been written yet. So if we were to write a huge enough blob, the output might look like this:
Do other stuff
Wrote to file!

This makes applictions very fast because you're not waiting on a client message, a file write or other. You can keep on processing the data in a parallel manner. This is considered by many one of the strengths of Node.js.

좋은 웹페이지 즐겨찾기