简体   繁体   English

在这个用例中使用 Promise 还是回调?

[英]Use Promise or callbacks in this use-case?

I have this use-case where I am not sure if it's better to use a Promise or not.我有这个用例,我不确定使用 Promise 是否更好。 The problem I see, is that I have a 3-case scenario:我看到的问题是,我有一个 3 种情况:

  • success成功
  • failure失败
  • abort(nothing happens)中止(什么也没发生)

My code-sample is here:我的代码示例在这里:


class MyView{

// ...

    /**
     * Saves the record changes. Process the uploads. 
     * If beforeSave returns true, nothing should happen.
     * If the view has uploads, process them before saving the record.
     *
     * @param {Callback|Function} success
     * @param {Callback|Function} failure
     */
    saveRecord: function (success, failure) {
        const me = this,
            view = me.getView();

        if (false === view.fireEvent('beforeSave')) {
            //this is the abort scenario
            return;
        }

        if (view.hasUploads()) {
            view.processUploads(() => {
                me.executeRecordSave(success, failure);
            });
        } else {
            me.executeRecordSave(success, failure);
        }
    },

    /**
     * Save the Record Effectively
     * @private
     * @param {Callback|Function} success
     * @param {Callback|Function} failure
     */
    executeRecordSave: function (success, failure) {
        const me = this,
            view = me.getView();

        const record = me.vmGet('record');

        RecordSaver.saveRecord(record, view, {
            success: success,
            failure: failure
        });
    },

// ...

}

The current usage is:目前的用法是:

const view = new MyView();

view.saveRecord(() => {
    console.log('success');
}, () => {
    console.log('success');
});

and I would like to replace it with a Promise:我想用 Promise 替换它:

const view = new MyView();

// would like to replace it with a Promise:
view.saveRecord().then(() => {
    console.log('success');
}, () => {
    console.log('success');
});

but in case of "abort" this Promise will never be fulfilled.但在“中止”的情况下,这个 Promise 将永远不会实现。

The only problem I see with the promise is this piece of code which will never fulfill the promise.我看到承诺的唯一问题是这段代码永远不会兑现承诺。

        if (false === view.fireEvent('beforeSave')) {
            return;
        }

so I am not sure if I actually use a Promise in this case.所以我不确定在这种情况下我是否真的使用了 Promise。

Or, other way, I could return a Promise which will NEVER be fulfilled in case of "abort".或者,换句话说,我可以返回一个在“中止”的情况下永远不会实现的承诺。 Is that ok?这可以吗?

I'm assuming both view.processUploads and RecordSaver.saveRecord return a promise (technically they should)我假设view.processUploadsRecordSaver.saveRecord返回一个承诺(技术上他们应该)

class MyView{

    // ...

    /**
     * Saves the record changes. Process the uploads. 
     * If beforeSave returns true, nothing should happen.
     * If the view has uploads, process them before saving the record.
     *
     * @param {Callback|Function} success
     * @param {Callback|Function} failure
     */
    saveRecord: async () => {
        // use arrow function so you don't need the "me = this"
        const view = this.getView();

        if (false === view.fireEvent('beforeSave')) {
            //this is the abort scenario
            return;
        }

        if (view.hasUploads())
            // Wait for the upload to end
            // the result of the upload should be 
            // saved in a private variable
            // to be used by _executeRecordSave()
            await view.processUploads();
        
        return this._executeRecordSave();
        
    },

    /**
     * Save the Record Effectively
     * @private
     */
    _executeRecordSave: () => {
        const view = this.getView();

        const record = this.vmGet('record');
        // return the saveRecord result as a Promise
        return RecordSaver.saveRecord(record, view);
    },

    // ...

}

Usage :用法 :

const view = new MyView();

view.saveRecord().then(result => {
    if(result === 'success') () => console.log('success') // success function
    if(result === 'failure') () => console.log('failure') // failure function
    if(!result) () => console.log('abort') // abort function
});

Also you need to add proper error handler for the upload errors.您还需要为上传错误添加适当的错误处理程序。

Ps: Can't test this code, it should work, sorry in advance if there is any error. Ps:无法测试此代码,它应该可以工作,如果有任何错误,请提前道歉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM