我通常要花几个小时来编写NodeJS代码,有一个常见的情况我不知道该如何面对。给定下面的异步函数调用(我们忘记了所需的回调):
function foo (callback) {
// Perform a task and call callback when finished
callback();
}
foo(); // We forget the callback
哪种方法更好?我找到两个选择:
1.使foo()
函数更健壮,将以下内容添加为第一行:callback = callback || function () {}
.
1.当foo()
尝试调用callback()
但它不存在时,让它崩溃。
也许第三种选择(我更喜欢)是最好的:如果未提供回调,则抛出自定义错误,如foo()
的第一行。例如:
function foo (callback) {
if (!callback) {
throw new Error('No callback provided');
}
// More stuff here
callback();
}
我的问题是:有没有什么著名的模式来解决这种情况?你认为哪种方法更好?你有没有用不同的方法来解决这个问题?
1条答案
按热度按时间mwecs4sa1#
It all depends if your callback is mandatory or not.
throw new Error('No callback provided');
.or in a single line: