jQuery Promises

by Kaeden

HTML

Click this
<br>
<button id="startOperation">Start Operation</button>
<hr>
Then click one of these
<br>
<button id="success">Success</button>
<br>
<button id="error">Error</button>

JavaScript

$(document).ready(function () {
    
    var remoteDeferred = null;

    var successCall = function (event) {
        var operationResult = {};
        operationResult.result = "success";
        remoteDeferred.resolve(operationResult);
    }
    
    var errorCall = function () {
        var operationResult = {};
        operationResult.result = "error";
        remoteDeferred.reject(operationResult);
    };
        
    var resultHandler = function(operationResult) {
        //This won't run until the deferred operation has completed
        alert("Result of operation: " + operationResult.result);
    };
    
    var start = function (event) {
        alert("Waiting for operation result");
        remoteDeferred = $.Deferred();
        remoteDeferred.promise().done(resultHandler).fail(resultHandler);
    };
    
    $("#success").click(successCall);
    $("#startOperation").click(start);
    $("#error").click(errorCall);
});