Example use promises of SweetAlert

SweetAlert uses promises to keep track of how the user interacts with the alert.

If the user clicks the confirm button, the promise resolves to true. If the alert is dismissed (by clicking outside of it), the promise resolves to null.

Example 1 : Get value of button

 

<!DOCTYPE html>

<html>

    <body>

        <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>

        <p>Example Alert use promises</p>

        <button onclick="run()">Run</button>

        <script>

            function run(){

           swal("Click on either the button or outside the modal.")

              .then((value) => {

                swal(`The returned value is: ${value}`);

              });

            }

        </script>

    </body>

</html>

 

Result:

 

 

 

Click OK:

 

 

Click outside modal:

 

 

Example 2 : Alert when user perform a dangerous action

 

<!DOCTYPE html>

<html>

    <body>

        <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>

        <p>Example Alert use promises</p>

        <button onclick="run()">Run</button>

        <script>

            function run(){

                swal({

                    title: "Are you sure?",

                    text: "Once deleted, you will not be able to recover this imaginary file!",

                    icon: "warning",

                    buttons: true,

                    dangerMode: true,

                })

                .then((willDelete) => {

                    if (willDelete) {

                      swal("Poof! Your imaginary file has been deleted!", {

                        icon: "success",

                      });

                    } else {

                      swal("Your imaginary file is safe!");

                    }

                });

            }

 

        </script>

    </body>

</html>

 

Result:

 

 

Click OK:

 

 

Click Cancel: