Node.js同步与异步 [英] Node.js sync vs. async

查看:78
本文介绍了Node.js同步与异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习node.js,我看到了2个同步和asycn程序示例(同一个).

I'm currently learning node.js and I see 2 examples for sync and asycn program (same one).

我确实了解回调的概念,但是我试图理解第二个(异步)示例的好处,因为即使差异有所不同,看来他们两个在做的事情完全相同.

I do understand the concept of a callback, but i'm trying to understand the benefit for the second (async) example, as it seems that the two of them are doing the exact same thing even though this difference...

能否请您详细说明第二个示例会更好的原因? 我很乐意得到更广泛的解释,这将有助于我理解这个概念.

Can you please detail the reason why would the second example be better? I'll be happy to get an ever wider explanation that would help me understand the concept..

谢谢!

第一个示例:

var fs = require('fs');

function calculateByteSize() {
    var totalBytes = 0,
        i,
        filenames,
        stats;
    filenames = fs.readdirSync(".");
    for (i = 0; i < filenames.length; i ++) {
        stats = fs.statSync("./" + filenames[i]);
        totalBytes += stats.size;
    }
    console.log(totalBytes);
}

calculateByteSize();

第二个示例:

var fs = require('fs');

var count = 0,
    totalBytes = 0;

function calculateByteSize() {
    fs.readdir(".", function (err, filenames) {
        var i;
        count = filenames.length;

        for (i = 0; i < filenames.length; i++) {
            fs.stat("./" + filenames[i], function (err, stats) {
                totalBytes += stats.size;
                count--;
                if (count === 0) {
                    console.log(totalBytes);
                }
            });
        }
    });
}

calculateByteSize();

推荐答案

第一个示例是全部阻塞I/O.换句话说,您需要等到readdir操作完成后才能遍历每个文件.然后,您需要阻止(等待)每个单独的同步状态操作,然后再继续操作下一个文件.在所有操作完成之前,calculateByteSize()调用之后无法运行任何代码.

Your first example is all blocking I/O. In other words, you would need to wait until the readdir operation is complete before looping through each file. Then you would need to block (wait) for each individual sync stat operation to run before moving on to the next file. No code could run after calculateByteSize() call until all operations are completed.

另一方面,异步(第二个)示例全部使用回调模式进行非阻塞.在这里,一旦调用fs.readdir(但在运行回调之前),就立即返回到calculateByteSize()调用之后.一旦readdir任务完成,它将执行对您匿名函数的回调.在这里,它循环遍历每个文件,并再次对fs.stat进行非阻塞调用.

The async (second) example on the otherhand is all non-blocking using the callback pattern. Here, the execution returns to just after the calculateByteSize() call as soon as fs.readdir is called (but before the callback is run). Once the readdir task is complete it performs a callback to your anonymous function. Here it loops through each of the files and again does non-blocking calls to fs.stat.

第二个更有利.如果您可以假装对readdir或stat的调用可以在250毫秒至750毫秒的范围内完成(这可能不是这种情况),那么您将在等待对同步操作的串行调用.但是,异步操作不会导致您在每次调用之间等待.换句话说,循环遍历readdir文件,如果您正在同步执行,则需要等待每个stat操作完成.如果您要异步执行此操作,则不必等待调用每个fs.stat调用.

The second is more advantageous. If you can pretend that calls to readdir or stat can range from 250ms to 750ms to complete (this is probably not the case), you would be waiting for serial calls to your sync operations. However, the async operations would not cause you to wait between each call. In other words, looping over the readdir files, you would need to wait for each stat operation to complete if you were doing it synchronously. If you were to do it asynchronously, you would not have to wait to call each fs.stat call.

这篇关于Node.js同步与异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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