Reference: jQuery Deferred Object
A deferred object registers callback functions that can be called when an asynchronous process is completed.
Parameter
- beforeStart - A function that is called just before the constructor returns.
Syntax
$.Deferred(beforeStart);
Example
Get a list of employees whose given name is "John"
function getEmployees(givenName) { return $.Deferred(function (deferred) { // Get the list of employees from the server. $.getJSON("/employee/list", function (list) { var employees = []; // Loop over the list of employees. If the employee givenName matches the givenName passed in, then // add the employee to the array of employees to be returned. for (var idx = 0; idx < list.length; idx++) { if (list[idx].givenName === givenName) { employees.push(list[idx]); } } // Resolve with the list of employees with the given name that was passed in. deferred.resolve(employees); }); }); } getEmployees("John").then(function (employees) { for (var idx = 0; idx < employees.length; idx++) { console.log(JSON.stringify(employees[idx])); } });