我已经用 Node 编写了几个 Express 应用程序,但我的知识存在着可耻的差距。请对我宽容一些。
在 Node.js 中使用这种传统格式的函数是否合适?
function isGreaterThanZero ( val ){
return val > 0;
}
还是应该始终使用回调?
function isGreaterThanZero (val, cb){
if (val > 0) {cb(true);}
else {cb(false);}
}
Node.js 的异步特性让我的大脑彻底翻转,我开始质疑一切。
最佳答案
当然合适
这用于同步代码
function isGreaterThanZero(val){
return val > 0;
}
通俗地说,当没有什么可等待的时候,您将使用同步函数。您将在下面提到的特殊情况之外使用同步函数
对于内存中的操作,例如基本计算、字符串操作、数组追加等,您可以使用同步函数。
但是,一些同步函数确实使用回调,但它们更多地用于映射或过滤目的。在评论中,我看到您询问了arr.filter
。其他函数,如 arr.forEach、arr.map 或 arr.reduce 接受回调,但它们不是隐式异步。在这种情况下,回调函数仅用于增强被调用函数的行为。
这适用于异步代码
function isGreaterThanZeroAsync(val, cb){
// some long process...
cb(val > 0);
}
当您有事情需要等待时,您将使用异步函数。通常是网络、文件系统或数据库访问。异步函数将允许您的函数立即返回(退出)(就像同步函数一样),但回调将在准备好后立即获取值。
这是一个小的异步演示
function demoAsync(cb) {
console.log("demo start");
setTimeout(function() {
cb("hello world");
}, 1000);
}
console.log("init");
demoAsync(function(val) {
console.log(val);
console.log("demo done");
});
console.log("init done");
输出
init
demo start
init done
// 1000 ms later...
hello world
demo done
为什么这很重要?
您会立即收到“init”
、“demo start
”和“init did
”。这表明在我们等待演示完成时,您的程序可以继续。
1000 ms
后,我们看到“hello world”
和“演示完成”
。
关于javascript - 在 Node 中使用 'return {value}' 是否合适?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29042728/