【问题标题】:Utlizing Promise To control Event Flow in VueJs在 VueJs 中使用 Promise 控制事件流
【发布时间】:2016-01-26 23:45:15
【问题描述】:

我有一个处理 HTTP 请求的 Vue 指令。我正在尝试做的是利用承诺并将 SweetAlert 挂钩到流程中。我首先启动 onRequestSubmit

    bind: function () {
        this.el.addEventListener('click', this.onRequestSubmit.bind(this));
    },

在 onRequestSubmit 中

    onRequestSubmit: function (e) {
        e.preventDefault();

        this.fireFlashMessage()
        .then(this.vm.$http[this.getRequestType()](this.el.getAttribute("data-delete-url"), this.aggregateData()))
        .then(this.onComplete.bind(this))
        .catch(this.onError.bind(this));
    },

我希望 fireFlashMessage 在用户确认时返回 true,以便 onRequestSubmit 可以委托请求。

我的问题是:我应该将 fireFlashMessage 包装在一个承诺中,并在调用成功返回时继续执行 then 吗?我对 Promises 很陌生,有点难以理解它们。

【问题讨论】:

  • 你知道你的代码暗示fireFlashMessage返回一个Promise,而不是一个布尔值 - 如果它返回true - 一个布尔值没有.then方法,所以代码注定失败

标签: javascript promise vue.js sweetalert


【解决方案1】:

SweetAlert 确认窗口使用回调函数,而不是承诺。然后在该回调中,您将使用类似的承诺

onRequestSubmit: function (e) {
    e.preventDefault();

    swal({
            title: "Are you sure?",  
            showCancelButton: true,   
            confirmButtonText: "Yes"
        }, 
        this.onRequestConfirm.bind(this)
    );
},
onRequestConfirm: function() {
    this.vm.$http[this.getRequestType()](this.el.getAttribute("data-delete-url"), this.aggregateData())
    .then(this.onComplete.bind(this))
    .catch(this.onError.bind(this));
}

编辑:删除 this.fireFlashMessage() 不再使用该函数,但如果你愿意,你可以再次重构它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    • 2016-03-20
    • 1970-01-01
    • 2023-03-06
    • 2016-05-31
    • 1970-01-01
    相关资源
    最近更新 更多