高效使用回调函数的例子

Examples of efficient use of callback functions

所以我理解回调本质上是传递给另一个函数并在稍后执行的函数。

我也知道许多主要库(例如 jQuery)有效地使用了回调,但我想要一个简单的代码示例以及关于何时最好使用回调函数来解决问题的解释问题。 到目前为止我看到的所有示例都是 setTimeout,但我想看一个新的示例来拓宽我对如何使用回调函数的看法。

最后,我想看看 1.回调函数的例子。 2. 为什么在那个例子中 solution/approach 是合适的。
3. 可能还有其他常见的 reasons/scenarios 用于使用回调。

非常感谢您!

函数是第一个 class 对象,我们可以将一个函数作为参数传递给另一个函数,然后执行传入的函数,甚至 return 稍后执行。这就是在 JavaScrip 中使用回调函数的本质 JAVA 脚本回调

示例:

   function test(data,function(datafromfunc){
           //my function
});

内部服务功能

  function(data,callback)
{
  //your logic
  callback(result)
}

示例 2 //JavaScript回调函数

function randomize(min, max, callback) {  
    var random = Math.ceil(Math.random() * (min - max) + max);
    callback(random);
}

randomize(5, 15, function(rndm) {
    alert(rndm);
});

当您必须处理您不知道需要多少时间来计算的函数(或方法)时,通常会使用回调。

例如,假设您需要从竖井取水来做某事,但您实际上并不知道这个竖井离您家的位置和距离:您请朋友(异步函数)好心地走到竖井那里,替你取水,这样他回来的时候你就可以用了。

与此同时,在等水的时候,你本可以做一些其他有用的事情。

一个基本的例子是:

function getWater(callback) {
    // Walk to the shaft
    // Take water
    // Go back home 
    // This function is asynchronous

    callback();
}

function useWater() {
    // Do what you needed to do with water
}

getWater(useWater);
// While waiting to use the water:
doUsefulThings();

在 JavaScript 中,我们有能力像对待其他 variables 一样对待 Functions

也就是说,传统上我们写这样一个函数:

function sayHello(name){
      console.log("Hello "+name);
}

然后通过必要的参数调用它:

sayHello("JavaScript");  

这几乎也是我们在其他脚本语言中使用函数的方式。

但是,如果我告诉你,在 JavaScript 中,functionvariable 一样好,在某种程度上它可以作为参数传递,当我们调用函数?

例如:

var sayHello = function(name){  // My callback method
  console.log(name);
};

function getNameAndSayHello(callback){
   var name = 'My name is a Sandeep'; // I do some other things here...
   //..........some other code.............
   //..... when i am done with other things, i call the callback method... 
   callback(name);

}

getNameAndSayHello(sayHello);

如您所见,我将 sayHello(一个函数)作为参数传递给另一个函数 getNameAndSayHello。简而言之,Functional Programming的精髓,虽然不是最纯粹的形式。

这种传递 functions 的能力就像任何其他 variable/value 一样,使我们在以后调用 callback 非常方便,这适合我们。

http://jsfiddle.net/wz9b1s8m/