【问题标题】:Chain To Then Function While Encapsulating One in ES6Chain To Then 函数同时在 ES6 中封装一个
【发布时间】:2020-03-21 20:02:43
【问题描述】:

我是一名新的 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));

但是当然;由于警报(result),在运行时控制台上给我“.askQuestion(...) is undefined”。

如何在 es6 中链接两个然后函数?

【问题讨论】:

  • 您忘记了askQuestion 中的return 语句。 (并且then() 回调是毫无意义的,因为它只是返回未修改的承诺的结果)
  • 从 askQuestion 中删除 then() 并直接返回 Swal.fire
  • 非常感谢@SajeebAhamed。它奏效了。
  • 不客气。

标签: javascript ecmascript-6 es6-promise sweetalert2


【解决方案1】:

你需要回报你的承诺:

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;}) 毫无意义,因此可以将其删除。

然后,当你使用它时,你必须将一个函数 reference 传递给.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()

【讨论】:

  • @lost_in_library - 确保您看到我刚刚添加到答案末尾的附加部分。
猜你喜欢
  • 1970-01-01
  • 2017-07-19
  • 2018-03-13
  • 2011-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-11
  • 2015-04-13
相关资源
最近更新 更多