javascript - promise 不返回对象

标签 javascript node.js image-processing

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

我纠正了几个问题并做了一些改进:

  1. 每当处理多个文件时,您的变量 file 就会被覆盖,因为您尝试在多个异步回调中使用同一变量。我将它放入一个闭包中,以便为正在处理的每个图像单独保存。这可能是导致它无法处理多个图像的主要问题。

  2. 您没有在正确的时间调用 next()(有时调用次数过多)。

  3. 您的错误处理存在多个问题,因为您不能仅从异步方法中返回来停止处理。

  4. 我决定,如果您无法删除临时文件,则处理应该继续而不是中止,因为这不是致命问题。

  5. 此代码使用 Promise.all() 在所有操作完成时获取回调,而不是使用手动计数器。这也使得错误处理变得更加简单。

关于javascript - promise 不返回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27282757/

相关文章:

javascript - D3 中使用内部 JSON 变量的堆叠条形图

javascript - 如何根据解析用户命令字符串为 HTML 元素着色

node.js 和处理重定向后的数据

javascript - Node.js readline 行事件回调保证在下一次调用之前完成?

python - numpy.resize 和 numpy.reshape 函数如何在 python 内部工作?

python - 在 OpenCV 返回图像中裁剪旋转 90 度

javascript - 将 Json 数据解码为 PHP 变量

javascript - 有没有办法使用 javascript 来阻止 javascript?

node.js - 使用 putObject 时 S3 文件损坏

OpenCV - 在背景减法器 MOG 中修复前景