node.js - 返回或不回调,对 Node 有影响吗

标签 node.js v8

我只是想知道返回回调是否有区别。

It was already asked here on SO但在 Node 环境中则不然,实际上任何 IO 功能都使用 CPS。我没有将这个问题标记为 Javascript,因为我认为它与语言无关,而是更具体地涉及 Nodejs 和 v8 内部的工作方式。

这两个版本的 foo 函数之间有什么区别(对于 V8)

// foo that returns cb();
function foo(cb) {
    fs.read(fd, buffer, 0, 10, 10, function(err, bytesRead, buffer) {
        return cb(buffer);
    });
}

// foo that won't return cb()
function foo(cb) {
    fs.read(fd, buffer, 0, 10, 10, function(err, bytesRead, buffer) {
        cb(buffer);
    });
}

最佳答案

在这种情况下不会,因为回调下面没有代码。如果您在回调下有代码,例如

// foo that won't return cb()
function foo(cb) {
    fs.read(fd, buffer, 0, 10, 10, function(err, bytesRead, buffer) {
        cb(buffer);
        console.log('yup')
    });
}

那么回调后代码会继续执行。但如果你添加 return 控制台将永远不会执行

// foo that won't return cb()
function foo(cb) {
    fs.read(fd, buffer, 0, 10, 10, function(err, bytesRead, buffer) {
        return cb(buffer);
        //will never execute below
        console.log('yup')
    });
}

关于node.js - 返回或不回调,对 Node 有影响吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21038808/

相关文章:

javascript - 通过ejs文件中的javascript访问JSON

javascript - 从 javascript 更新 google 联系人时出现问题

javascript - 监控 Node.js 进程以了解每个进程的最大内存使用量

javascript - 当前或最受支持的 NodeJS 框架/lib 选项?

javascript - Node Grunt.js 'Warning: connect is not defined Use '

node.js - 通过 node-http-proxy 代理 WebSockets 不起作用

javascript - 使用 PhantomJS 桥序列化函数

node.js - 为 ARM6 (Raspberry Pi) 交叉编译 Node.js

javascript - 编写高性能 Javascript 代码而不去优化

javascript - Object.__proto__ 中有什么?