promise 后数组中未定义的值:
我使用 Q 通过 Node.js 管理 Promise,并使用 easyImage 处理图像。
这段代码工作正常,它从 tmp 文件夹加载、保存、剪切图像并将其粘贴到用户文件夹中。我遇到的唯一问题是将最终数据保存到数据库中。我在数组中得到未定义的值...
exports.postAccountImages = function(req, res, next) {
User.findById(req.user.id, function(err, user) {
var path = __dirname + '/../public/images/u/' + user._id + '/';
var max = 800;
fs.exists(path, function(exists) {
if (!exists) fs.mkdirSync(path);
});
var promises = [];
for (var key in req.files) {
if (req.files.hasOwnProperty(key)) {
(function(file) {
q().then(function() {
return promises.push(easyimg.info(file.path).then(function(image) {
easyimg.resize({
src: file.path,
dst: path + file.name,
width: (image.width >= max) ? max : image.width,
height: (image.height >= max) ? max : image.height,
quality: 80
}).then(function(image) {
fs.remove('./tmp-uploads/' + image.name);
return {
src: image.name,
main: false
};
});
}));
});
})(req.files[key]);
}
}
q.all(promises).then(function(result) {
console.log(result); // [undefined, undefined, undefined, ...]
// Here I should push result to the DB
});
});
};
最佳答案
以下是如何执行此操作的一般想法(未经测试):
var promises = [];
for (var key in req.files) {
if (req.files.hasOwnProperty(key)) {
(function(file) {
promises.push(easyimg.info(file.path).then(function(image) {
return easyimg.resize({
src: file.path,
dst: path + file.name,
width: Math.max(image.width, 800),
height: Math.max(image,height, 800),
quality: 80
}).then(function(image) {
fs.remove('./tmp-uploads/' + image.name, function(err) {
if (err) {
// logging error, but not stopping execution
// since this is a non-fatal error
console.log("err removing temp upload: ", err);
}
});
return {src: file.name, main: false};
});
}));
})(req.files[key]);
}
}
// now wait for all promises to finish
// assumes you want to call next() no matter what when all image processing is done
Promise.all(promises).then(function(results) {
// all results are in the results array here
// do whatever processing of the results array you want to do here
res.sendStatus(200);
next();
}, function() {
// set some status to send when there's an error
res.sendStatus(xxx);
next();
});
我纠正了几个问题并做了一些改进:
每当处理多个文件时,您的变量
file
就会被覆盖,因为您尝试在多个异步回调中使用同一变量。我将它放入一个闭包中,以便为正在处理的每个图像单独保存。这可能是导致它无法处理多个图像的主要问题。您没有在正确的时间调用
next()
(有时调用次数过多)。您的错误处理存在多个问题,因为您不能仅从异步方法中返回来停止处理。
我决定,如果您无法删除临时文件,则处理应该继续而不是中止,因为这不是致命问题。
此代码使用
Promise.all()
在所有操作完成时获取回调,而不是使用手动计数器。这也使得错误处理变得更加简单。
关于javascript - promise 不返回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27282757/