Search code examples
javascriptecmascript-6es6-promisesweetalert2

Chain To Then Function While Encapsulating One in ES6


I'm a new ecmaScript6-student. I need to chain to "then" promises while encapsulating a library function.
Swal is sweetAlert2 function to ask questions and get response from user, yes/no.

Here is what I'm trying to do;

class MyLib {

    constructor() {
    }

    static askQuestion(title, message){
        Swal.fire({
            title: title,
            text: message,
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!'
        }).then((result) => {
            return result;
        })
    }
}

Then call this function like;

MyLib.askQuestion("Are you sure?", "Are you sure you want to delete this ?").then(alert(result));

But ofcourse; on runtime console gives me ".askQuestion(...) is undefined" because of the alert(result).

How do I chain two then function in es6 ?


Solution

  • You need to return your promise:

    class MyLib {
    
        constructor() {
        }
    
        static askQuestion(title, message){
            return Swal.fire({
                title: title,
                text: message,
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, delete it!'
            });
        }
    }
    

    And, as others have said, your .then(result => {return result;}) was pointless so it can be removed.

    Then, when you use it, you have to pass a functon reference to .then() so change this:

    MyLib.askQuestion("Are you sure?", "Are you sure ...").then(alert(result));
    

    to this:

    MyLib.askQuestion("Are you sure?", "Are you sure ...").then((result) => alert(result));
    

    or this:

    MyLib.askQuestion("Are you sure?", "Are you sure ...").then(alert);
    

    And, if Swal.fire() can ever reject it's promise, you need a .catch() too.