我所需要做的就是在当前函数执行结束时执行一个回调函数。

function LoadData() 
{
    alert('The data has been loaded');
    //Call my callback with parameters. For example,
    //callback(loadedData , currentObject);
}

这个函数的消费者应该是这样的:

object.LoadData(success);

function success(loadedData , currentObject) 
{
  //Todo: some action here 
}

我怎么实现这个呢?


当前回答

有些答案虽然正确,但理解起来可能有点棘手。下面是一个外行术语的例子:

var users = ["Sam", "Ellie", "Bernie"];

function addUser(username, callback)
{
    setTimeout(function()
    {
        users.push(username);
        callback();
    }, 200);
}

function getUsers()
{
    setTimeout(function()
    {
        console.log(users);
    }, 100);
}

addUser("Jake", getUsers);

回调意味着,在使用console.log显示用户列表之前,总是将“Jake”添加到用户中。

源(YouTube)

其他回答

当调用回调函数时,我们可以像下面这样使用它:

consumingFunction (callbackFunctionName)

例子:

// Callback function only know the action,
// but don't know what's the data.
function callbackFunction(unknown) {
  console.log(unknown);
}

// This is a consuming function.
function getInfo(thenCallback) {
  // When we define the function we only know the data but not
  // the action. The action will be deferred until excecuting.
  var info = 'I know now';
  if (typeof thenCallback === 'function') {
    thenCallback(info);    
  }
}

// Start.
getInfo(callbackFunction); // I know now

这是Codepend的完整示例。

function LoadData(callback) 
{
    alert('the data have been loaded');
    callback(loadedData, currentObject);
}
function loadData(callback) {

    //execute other requirement

    if(callback && typeof callback == "function"){
        callback();
   }
}

loadData(function(){

   //execute callback

});

在尝试执行回调函数之前,最好确保它是一个实际的函数:

if (callback && typeof(callback) === "function") {

  callback();
}

Try:

function LoadData (callback)
{
    // ... Process whatever data
    callback (loadedData, currentObject);
}

函数是JavaScript中的第一类;你可以四处传阅。