简体   繁体   中英

Return response of jquery.deferred object when call the function

I am trying to create custom dialog box and I return the response of what the user click in that dialog. I use the deferred object but it returns immediately when i call the function.

Example fiddle

When I call the function

var value = showDelete("Hello World");

which always return undefined instead of "Ok" or "Cancel".

What am I done wrong in this code. Help me. Thanks in advance.

First, you need to return deferred object from showDelete method.

Second, in your event handler the variable value is a deferred object, so you need to use done method to get the value. Check this code, it seems to work:

function showDelete(msg){
    var defers = $.Deferred();
    jQuery.when(showAlert(msg)).done(function(){
        alert("Ok");
        defers.resolve("ok");    // resolve, not return value
    }).fail(function(){
        alert("Cancel");
        defers.resolve("cancel");   // resolve, not return a value
    }).always(function(){
        jQuery("#confirm").hide();
    })
    return defers.promise();    // return a promise
}
function showAlert(msg){
    var defer2 = $.Deferred();
    jQuery("#msg").html(msg);
    jQuery("#confirm").show();
    jQuery("#confirm input:first").on("click",function(){
        defer2.resolve();
    });
    jQuery("#confirm input:last").on("click",function(){
        defer2.reject();
    });
    return defer2.promise();
}
jQuery("#alertt").bind("click", function(){
    var value = showDelete("Hello World");
    value.done(function(result){    // use done handler
        console.log(result); //logs ok or cancel;
    });
});

Additionally, usage of deferred objects in your scenario seems unnecessary. The main usage of deferred is to simplify working with long running asynchronous tasks (eg AJAX), but in your case it looks like methods without deferred would be as effective.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM