简体   繁体   English

我应该在自定义函数中使用回调模式吗? 节点js

[英]shall I use callback pattern in my custom function? node js

for example I have a function A that has to return some value 例如我有一个必须返回一些值的函数A

    function A(callback){
        //some computation
        var fakeData = 20;
        callback(null,fakeData)
    }
    function B(err,data){
      if(!err){
 console.log(data);
}

    }
A(B);

so as far as I know only I/O operations in node js runs asynchronously, so whats the difference if I right just this 据我所知,只有节点js中的I / O操作是异步运行的,所以如果我对此正确的话有什么区别

   function A(){

            var fakeData = 20;
            return fakeData;
        }
        function B(data){

     console.log(data);

        }
      var data = A();
      B(data);

I mean both of them will run synchronously right? 我的意思是两个都将同步运行,对吗?

The callback pattern is useful for a number of types of problems: 回调模式对于许多类型的问题很有用:

  1. When your function uses asynchronous operations and you want to be able to notify the caller when the asynchronous operations are complete and perhaps pass a final result to the caller. 当您的函数使用异步操作并且您希望能够在异步操作完成时通知调用方,并且可能将最终结果传递给调用方。

  2. When your function wants the caller to supply some function that can be used in the computation of a result as in the callback that can be passed to array.sort(callback) . 当您的函数希望调用者提供一些可以在结果计算中使用的函数时,例如可以传递给array.sort(callback)

You would generally NOT use a callback pattern to communicate the result of a synchronous operation because that just makes the code more complicated than just directly returning the result from the function. 通常,您将不使用回调模式来传达同步操作的结果,因为与直接从函数返回结果相比,这会使代码更加复杂。 So, if all your operations in A() are synchronous, then your second code option will be simpler to code and use. 因此,如果您在A()中的所有操作都是同步的,则您的第二个代码选项将更易于编码和使用。

如果您在谈论这两个函数,那么是的,这两个是相同的,但这不是使用回调,因为当您有一个在一段时间后或将来会返回结果的过程(如数据库调用或REST API)时,将使用回调调用或文件读/写操作,我们不确定它们何时返回结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM