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

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 
}

我怎么实现这个呢?


当前回答

我的2美分,相同但不同…

<script>
    dosomething("blaha", function(){
        alert("Yay just like jQuery callbacks!");
    });


    function dosomething(damsg, callback){
        alert(damsg);
        if(typeof callback == "function") 
        callback();
    }
</script>

其他回答

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

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

  callback();
}
function LoadData(callback) 
{
    alert('the data have been loaded');
    callback(loadedData, currentObject);
}
     function login(email, password, callback) {
         //verify the user
         const users = [
          { email: "abc@gmail.com", password: "123" },
          { email: "xyz@gmail.com", password: "xyz" }
         ];

         const user = users.find(
           (user) => user.email === email && user.password === password
         );
         callback(user);
       `enter code here`}

    function redirect(user) {
       if (user) {
          //user is successfully logged in
          console.log("user is successfully logged in ");
       } else {
         console.log("Incorrect credentials ");
       } 
    }

    
    login("abc@gmail.com", "123", redirect);

我希望这个例子能帮助所有想了解JS中回调的人

如果你想在某件事完成时执行一个函数。一个很好的解决方案是监听事件。 例如,我将实现一个Dispatcher,一个DispatcherEvent类与ES6,然后:

let Notification = new Dispatcher()
Notification.on('Load data success', loadSuccessCallback)

const loadSuccessCallback = (data) =>{
   ...
}
//trigger a event whenever you got data by
Notification.dispatch('Load data success')

调度员:

class Dispatcher{
  constructor(){
    this.events = {}
  }

  dispatch(eventName, data){
    const event = this.events[eventName]
    if(event){
      event.fire(data)
    }
  }

  //start listen event
  on(eventName, callback){
    let event = this.events[eventName]
    if(!event){
      event = new DispatcherEvent(eventName)
      this.events[eventName] = event
    }
    event.registerCallback(callback)
  }

  //stop listen event
  off(eventName, callback){
    const event = this.events[eventName]
    if(event){
      delete this.events[eventName]
    }
  }
}

DispatcherEvent:

class DispatcherEvent{
  constructor(eventName){
    this.eventName = eventName
    this.callbacks = []
  }

  registerCallback(callback){
    this.callbacks.push(callback)
  }

  fire(data){
    this.callbacks.forEach((callback=>{
      callback(data)
    }))
  }
}

编码快乐!

p/s:我的代码缺少处理一些错误异常

function loadData(callback) {

    //execute other requirement

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

loadData(function(){

   //execute callback

});