NodeJS中未提供回调模式

ajsxfq5m  于 2022-12-12  发布在  Node.js
关注(0)|答案(1)|浏览(92)

我通常要花几个小时来编写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();
}

我的问题是:有没有什么著名的模式来解决这种情况?你认为哪种方法更好?你有没有用不同的方法来解决这个问题?

mwecs4sa

mwecs4sa1#

It all depends if your callback is mandatory or not.

  • If it is mandatory then you should fail fast and do the throw new Error('No callback provided'); .
  • If it is optional then the standard practice is that you just call it if it exists. Instead of creating a new function, just add a check in the place where it is gonna get called:
if ( callback ) {
   callback();
}

or in a single line:

callback && callback();

相关问题