Loopback - 异步上传后更改对象属性

Loopback - Changing object attribute after asynchronous upload

我正在使用 Loopback,我想创建一个记录上传次数的上传界面。我将自己的模型与存储组件一起使用。

我正在使用存储组件的上传功能,我想在上传成功后更新对象属性 'uploadedPictures'(参见下面的代码)。我有一个问题,我不知道如何以安全的方式在异步方法之后使用 'this'-reference。例如。如果我的函数有很多调用,该属性只计算一次。

module.exports = function(Upload) {
    Upload.prototype.upload = function(ctx, options, cb) {
        if (!options)
            options = {};
        ctx.req.params.container = 'common';        

        // starting the upload and wait for the result
        var promise = new Promise(function(resolve, reject) {
            Upload.app.models.container.upload(ctx.req, ctx.result, options, function(err, fileObj) {
                if (err) {
                    console.error('error occured during upload');
                    cb(err);
                }
                else {
                    var fileInfo = fileObj.files.file[0];
                    resolve(fileInfo);
                }
            });
        });
        var uploadObject = this; // not safe, but how should I do it?
        // count 'uploadedPictures' up, but only if upload was successful
        promise.then(function(fileInfo) {
            uploadObject.uploadedPictures++;
            uploadObject.save();
        })
        .catch(function(e) {
            console.error('error: '+e);
        });
        cb(null, this);
    };

    Upload.remoteMethod('upload', {
        description : 'Uploads a file',
        accepts : [ {
            arg : 'ctx',
            type : 'object',
            http : {
                source : 'context'
            }
        }, {
            arg : 'options',
            type : 'object',
            http : {
                source : 'query'
            }
        } ],
        returns : {
            arg : 'fileObject',
            type : 'object',
            root : true
        },
        isStatic : false,
        http : {
            verb : 'post'
        }
    });
};

好吧,我找到了一个肮脏的解决方案,但它确实有效。我用 'findById'.

搜索对象本身
Upload.prototype.upload = function(ctx, options, cb) {
    if (!options)
        options = {};
    ctx.req.params.container = 'common';

    var _this = this;       
    Upload.app.models.container.upload(ctx.req, ctx.result, options, function(err, fileObj) {
        try {
            var files = fileObj.files.file;
            console.log('upload success): '+JSON.stringify(files));
            if (files.length > 0) {
                Upload.findById(_this.id, function(err, res) {
                    res.onUploadSuccess(cb);
                });
            }
            else {
                cb(null, _this);
            }
        }
        catch (err) {
            console.error('WARN: Upload not successful: ' + err);
            cb(err, null);
        }
    });
};

Upload.prototype.onUploadSuccess = function(cb) {
    this.uploadedPictures++;
    this.save();
    cb(null, this);
}