【问题标题】:Cleaning up promises (flattening and error handling)清理承诺(扁平化和错误处理)
【发布时间】:2013-09-04 18:46:04
【问题描述】:

我正在使用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' 重用的同时保持其可读性的任何帮助将不胜感激。

【问题讨论】:

    标签: javascript promise when-js


    【解决方案1】:

    第 1 步和第 2 步都共享同一个 'database.then',所以我想使用它,但我不知道如何扁平化 promise。

    您已经重复使用相同的 database 承诺两次(这很好),您只是在该承诺的两个不同映射之后,在这种情况下使用两个不同的 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!")
    });
    

    【讨论】:

      猜你喜欢
      • 2015-07-03
      • 1970-01-01
      • 1970-01-01
      • 2015-07-29
      • 1970-01-01
      • 2020-04-11
      • 2020-07-01
      • 2020-08-17
      • 2018-06-01
      相关资源
      最近更新 更多