简体   繁体   中英

Are Promises in JavaScript like Exception Handling in Java?

Just like the try(), catch() and throw() in Java as an exception handling is like then() and catch() in JavaScript as a promise!? Just a beginner asking some questions. Please don't judge. xD

Not really.. In JavaScript we have try/catch block as well.

Main benefits of Promises in JavaScript are things like Chaining.

The equivalent of Promises in Java is CompletableFuture . read about :)

No, they're quite different. Exception handling handles exceptions. Promises are a way to return values and act on them in an asynchronous environment, which JavaScript is.

Suppose you want to customize the JS confirm box. You could set up a jQuery dialog box, and return yes or no, depending on which button the user clicked. Like this:

function msgBoxConfirm(msgText, e) {
    e.preventDefault();               // Cancel the default behavior
    e.stopPropagation();              // Stop any other events from firing down the line
    $('#myDialogDiv').html(msgText).dialog({
        modal: true,
        title: boxTitle,
        buttons: {
            'Yes': function() {
                $(this).dialog('close');
                return true;
            },
            'No': function() {
                $(this).dialog('close');
                return false;
            }
        }
    });
}

Now, you call your message box function:

var retval = msgBoxConfirm('Do you really want to do that?', e);
if (!retval) {
    //Do the no behavior
} else {
    //Do the yes behavior
}

What you will find is that this code will continue before it finds out the value of retval , so retval will have a value of undefined when you evaluate it with the if . This is what it means to be asynchronous; the call to your function doesn't wait until the function is done executing before it moves on, potentially causing all sorts of bad behavior.

Promises are a way of waiting until the value is returned before checking it. To see how to set up this example properly using promises, see this .

try/catch detect the error itself and transfer control to catch part. this syntax exists in js too.

but in then/catch , you must notify occurring an error yourself (with calling reject ). This means you can notify error when you recognize an error is occurred. that error can be a real or not real error (programming/logical error).

Promises and exception handling are different, they are not same. In javascript promises give us a away to use . then to know when the function has completed its execution , it helps to know when async functions have completed its execution,and javascript also provides try/catch support as you know as that of java.

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