javascript - 清理 promise (扁平化和错误处理)

标签 javascript promise when-js

我正在使用 when 库并有一些如下代码:

when.join(
    database.then(function(db) {
        return db.collection("incidents");
    }).then(function(col) {
        return col.idExists(incidentId);
    }),
    database.then(function(db) {
        return db.collection("images");
    }),
    elib.uploadToS3(pic.path, 'image_uploads/' + id, pic.type)
).spread(function(exists, images, url) {
    if(!exists) {
        throw new Error("Incident id does not exist");
    }

    console.log("Image sucessfully uploaded to: ", url);
    return images.insert({
        _id: id,
        size: pic.size
    });
}).then(function() {
    console.log("At this point, it's totally succesfully recorded in the database!")
});

代码可读性不错,但逻辑是:

  1. 确保 eventId 有效
  2. 获取图像表
  3. 将图像上传到 S3

这三者可以同时发生。步骤 1 和步骤 2 都共享相同的“database.then”,所以我想使用它,但我不知道如何压平 promise 。

如果有任何问题(包括 eventId 无效),我应该调用 elib.deleteFromS3('image_uploads/' + id);

如果一切成功,我就准备通过在数据库中添加新条目来“提交”: images.insert({ _id: id, size: pic.size })

如果有效,我们就完成了。如果没有,我还需要再次从 S3 中删除。

在满足错误处理和“database.then”重用的同时保持可读性的任何帮助都将受到极大的赞赏。

最佳答案

Step 1 and 2 both share the same 'database.then', so I'd like to use that, but I don't know how to flatten promises.

您已经重复使用了相同的database promise 两次(这很棒),您只是在该 promise 的两个不同映射之后,并且使用两个不同的then<是非常合乎逻辑的 在这种情况下调用。试图用一个来做到这一点是不合理的,而且显然不会给你带来任何好处。

在我确定有操作理由之前,我也不会乱动 S3。 因此,只有在 id 存在后,我才会执行 1 并继续执行 2 和 3:

database.then(function(db) {
  return db.collection("incidents");
}).then(function(col) {
  return col.idExists(incidentId);
}).then(function (exists) {
  if (!exists) throw new Error("Incident id does not exist");
  return when.join(
    database.then(function(db) {
      return db.collection("images");
    }),
    elib.uploadToS3(pic.path, 'image_uploads/' + id, pic.type)
  ).spread(function(images, url) {
    console.log("Image sucessfully uploaded to: ", url);
    return images.insert({
      _id: id,
      size: pic.size
    })(null, function (err) {
      return elib.deleteFromS3('image_uploads/' + id).then(function () {
       throw err;
      });
    });
}).then(function() {
  console.log("At this point, it's totally succesfully recorded in the database!")
});

关于javascript - 清理 promise (扁平化和错误处理),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18581878/

相关文章:

javascript - 美国队长与 svg

javascript - 匹配以前缀开头的子字符串

javascript - 检索 Observable 内的值

javascript - $.when.apply 应用于 Promise 数组

javascript - 如何正确配置这个虚拟 Angular 项目

javascript - RETURN 如何应用在嵌套的 Promise 中

node.js - 'when-js' 或基本 amqplibrabbitmqnodejs 教程不起作用

javascript - 轻松 bundle 含 require 指令的 JavaScript 文件的方法

javascript - 为什么 JavaScript 跨浏览器不一致?