Search code examples
javascriptsweetalert2

SweetAlert2 executing functions while showing loading showing success after done


I am trying to create a sweetAlert2 function where I want to fire a loading screen. And during the loading screen, I want to execute some functions, which can take some time. Afterward I want to display a fire success or error, depending on what the return will be. I tried several methods:

Swal.fire({
            title: 'Auto close alert!',
            html: 'In progress',
            timerProgressBar: true,
            didOpen: () => {
                try {
                    Swal.showLoading();
                    call other functions..
                    if success show 
                    Swal.fire({
                     icon: 'success',
                     title: 'Success...',
                     html: message
                    });
                   or else fire error
             catch(err){
                etc.
           }
       }
      )};

Now when I execute the function it waits a few seconds (executing functions) and then it shows the success or error fire, but it doesn't show the in-progress loading dialog first. Any idea how to get this?


Solution

  • Fixed it by using setTimouts and promises:

     //Start 
            Swal.fire({
                        title: 'In progress',
                        html: 'Please wait while your action is being carried out.',
                        timerProgressBar: true,
                        didOpen: () => {
                        //here it will open the in progress box
                            Swal.showLoading();
        
                            //setTimeout with 1000 or more ms is needed in order to show the inprogress box
                            setTimeout(async () => {
                                let currentRecID = currentRecord.get().id;
        
                                //load complete record
                                currentRec = record.load({
                                    type: record.Type.OPPORTUNITY,
                                    id: currentRecID,
                                    isDynamic: true
                                });
        
                                const promiseVar = () =>
                                    new Promise((resolve, reject) => {
                                        resolve(canCreateORD(currentRec));
                                    });
                                canORDbeCreated = await promiseVar();
                                //Automatically close popup so it continues with willClose
                                Swal.close();
                            }, 1000);
        
                    
                        },
                        willClose: () => {
            //Show success / error box with Swal.fire