Introduction
Deferred often refers to something that has been delayed. Similarly, delayed objects are postponed and wait to execute until their state is resolved or rejected before they begin to execute. A chainable utility object known as the Deferred object is generated by invoking jQuery.Deferred() function. It was first introduced in jQuery 1.5. It may launch callback queues, add additional callbacks to callback queues, and relay if any synchronous or asynchronous function has succeeded or failed.
Understand defer with a simple example
var objDef = function() { var dfds = $.Deferred(); --Created deferred object dfd.resolve(); -resolve / reject it OR it remains unresolved return dfds; --returning deferred object } objDef ().done(function() --see if deferred object is resolved or rejected only then is here success --or fail method execute { alert("success"); }).fail(function() { alert("fail..."); });
- If you comment out the dfds.resolve() function in the example above, no alarm message is shown. Recall that delayed objects are only performed if they are resolved or refused.
- When you execute the success method using the resolve() method on a delayed object, the alert shows a success message.
- The alert will display the fail message if the reject() method is used on a delayed object since it invokes the fail function.
- Currently, use dfds.reject() and check instead of dfds.resolve(). You’ll receive a fail message in the alert. The deferred object is now clear.
- Invoking a delayed object like objDef right now (). Once done(), anybody can alter it by executing objDef .reject ().
- How therefore can it be made secure so that others cannot abuse it? Using the promise() method is the solution. The state of a delayed object cannot be changed outside the scope of that function. Use return dfd in place of delayed objects like return dfd. promise();
var objDef = function() { var dfds = $.Deferred(); const myTimeout = setTimeout(function() { dfds.reject("argument value"); }, 5000); return dfds.promise(); } defObj().then(function(data) { alert("sucess" + data); }, function(data) { alert("reject" + data); });
- In the aforementioned illustration, we utilize the setTimeout function to postpone converting the deferred object status to rejected, resulting in a 5-second warning period. This is a true usage of a delayed object since it prevents the execution of the object until that time.
- In the real scenario, you want to do some ajax call, and then on that success or failure, you want to invoke some method passing some arguments.
- When using resolve(args), you can give arguments or refuse (args).