然后将其封装在ES6中时起作用

我是一名新的ecmaScript6学生。 我需要在封装库函数时链接到“ then” promise。
Swal是sweetalert2函数,用于询问问题并获得用户的答复,是/否。

这就是我想要做的事

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;
        })
    }
}

然后像这样调用该函数;

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

当然可以;在运行时控制台上,由于警报(结果),显示“ .askQuestion(...)未定义”。

如何在es6中链接两个然后起作用的函数?

dqlovedq 回答:然后将其封装在ES6中时起作用

您需要兑现您的承诺:

class MyLib {

    constructor() {
    }

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

而且,正如其他人所说,您的.then(result => {return result;})毫无意义,因此可以将其删除。

然后,当您使用它时,必须将功能键引用传递给.then(),因此请进行以下更改:

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

对此:

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

或者这个:

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

而且,如果Swal.fire()能够兑现承诺,那么您也需要.catch()

本文链接:https://www.f2er.com/2605410.html

大家都在问