簡體   English   中英

清理承諾(扁平化和錯誤處理)

[英]Cleaning up promises (flattening and error handling)

我正在使用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. 確保incidentId有效
  2. 獲取圖像表
  3. 將圖像上傳到S3

所有這三個都可以同時發生。 第1步和第2步共享相同的'database.then',所以我想使用它,但我不知道如何壓扁承諾。

如果有任何問題(包括incidentId無效),我應該調用elib.deleteFromS3('image_uploads/' + id);

如果這一切都成功了,我准備通過在數據庫中添加一個新條目來“提交”: images.insert({ _id: id, size: pic.size })

如果有效,我們就完成了。 如果沒有,我仍然需要再次從S3中刪除。

任何幫助保持這種可讀性同時滿足錯誤處理和'database.then'重用將是非常感謝。

第1步和第2步共享相同的'database.then',所以我想使用它,但我不知道如何壓扁承諾。

你已經重復使用同一個database承諾的兩倍(這是偉大的),你只要以后承諾的兩種不同的映射是,這是非常合乎邏輯的使用兩個不同的then在這種情況下調用。 試圖用一個這樣做是不合理的,顯然不會給你帶來任何好處。

在我確定有操作原因之前,我也不會亂用S3。 所以我會做1並在id存在后繼續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!")
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM