Javascript 清理承诺(扁平化和错误处理)
我正在使用Javascript 清理承诺(扁平化和错误处理),javascript,promise,when-js,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("im
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!")
});
代码可读性较好,但逻辑是:
elib.deleteFromS3('image_uploads/')+id)代码>
如果全部成功,我准备通过在数据库中添加一个新条目来“提交”:
images.insert({u id:id,size:pic.size})
如果这行得通,我们就完了。如果没有,我仍然需要再次从S3中删除
在满足错误处理和“database.then”重用要求的同时,如果能帮助您保持可读性,我们将不胜感激
第1步和第2步都共享同一个“database.then”,所以我想使用它,但我不知道如何降低承诺
您已经两次重用了相同的数据库
promise(这很好),只需要两个不同的promise映射,在这种情况下使用两个不同的然后
调用是非常合乎逻辑的。试着用一个这样做是不合理的,显然也不会给你带来任何好处
我也不会搞乱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!")
});