gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:19:55 25 4
gpt4 key购买 nike

我正在使用 Loopback,我想创建一个记录上传数量的上传接口(interface)。我将自己的模型与存储组件一起使用。

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

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

关于javascript - Loopback - 异步上传后更改对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33785970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com