Callbacks


A callback function is a function passed into another function as an argument.
This can then be invoked inside the outer function to complete some kind of routine or action.


Synchronous callback


function greeting(name) { 
  alert('Hello ' + name);
}

function processUserInput(callback) {
  var name = prompt('Please enter your name.');
  callback(name);
}

processUserInput(greeting);

function ask(question, yes, no) { 
  if (confirm(question)) yes()
  else no();
}

ask(
  "Do you agree?",
  function() { alert("You agreed."); },
  function() { alert("You canceled the execution."); }
);


Asynchronous Callback


function asyncMethod(message, callback_function) { 
  setTimeout( function() {
    console.log(message);
    callback_function();
   }, 400)
}

asyncMethod('Connect to Database', function() {
}


Nested Callbacks


asyncMethod('Connect to Database', function() { 
  asyncMethod('Verify User Details', function() {
    asyncMethod('Check Permissions', function() {
      asyncMethod('Update User', function() {} )
    })
  })
})

Best Practices

Arguments should be (err, results)
Always 'return' when you want to exit



© 2022 Better Solutions Limited. All Rights Reserved. © 2022 Better Solutions Limited TopPrevNext