我有以下情况;
代码
projectService.getProject(ID)
.then(function (project) {
if (!project) {
return commonService.sendResponse(res, 404);
}
fileService.handleFileUpload(ID, [].concat(req.files.file))
.then(function (files) {
return commonService.sendResponse(res, 200, assets);
});
})
.catch(function (err) {
return commonService.sendError(res, err);
})
.finally(function cleanup() {
console.log('Fileupload completed');
});
注意:快乐路径流有效但是如果不满足某些条件,handleFileUpload可能会返回错误。如果此方法返回错误,则catch返回正确的错误,但在日志中我看到以下内容:
[TypeError: Cannot call method 'then' of undefined]
12:44:30.815 service [ERROR] Cannot call method 'then' of undefined (TypeError)
它抱怨的内容如下:
.then(function (files) {
handleFileUpload如下所示:
var handleFileUpload = function (projectId, fileList) {
var deferred = Promise.defer();
var reject = function (err) {
deferred.reject(err);
};
if (!(containsThumb(fileList)){
return reject(new Error('Missing thumbnail in request'));
}
/** some some logic **/
return deferred.promise;
};
}
exports.handleFileUpload = handleFileUpload;
一切都有用!但是无法找出记录异常的问题。
感谢任何帮助。
Ĵ
答案 0 :(得分:1)
您缺少一些returns
,在这种情况下,预期会返回承诺的函数不会这样做:
projectService.getProject(ID)
.then(function (project) {
if (!project) {
return commonService.sendResponse(res, 404);
}
return fileService.handleFileUpload(ID, [].concat(req.files.file))
// ^^^^^^ you will want to wait with `.catch` for this
.then(function (files) {
return commonService.sendResponse(res, 200, assets);
});
})
.catch(function (err) {
return commonService.sendError(res, err);
})
.finally(function cleanup() {
console.log('Fileupload completed');
});
var handleFileUpload = function (projectId, fileList) {
var deferred = Promise.defer();
var reject = function (err) {
deferred.reject(err);
return deferred.promise;
// ^^^^^^
};
if (!(containsThumb(fileList)){
return reject(new Error('Missing thumbnail in request'));
// this ^^^^^^ method must always return a promise
}
/** some some logic **/
return deferred.promise;
};
}
哦,并确保第二个功能不使用deferred antipattern。