gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:23:45 26 4
gpt4 key购买 nike

我正在使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com