【发布时间】:2019-05-12 16:56:48
【问题描述】:
我重构了我的代码,代码更简洁,没有重复。 但我想知道在我的场景中使用 $q.all 是否是最佳选择...
代码逻辑:
- 我有一个“可选”的承诺。在一种情况下,我需要调用外部 API(= promise),在另一种情况下,我不需要外部调用(= no promise)。
- 所以我创建了一个变量,我可以在其中存储承诺(或
null用于没有承诺的场景)。 -
$q.all等待承诺,然后检查返回值是否是承诺返回的值(场景 1)或null(场景 2)。
重构前的函数
model.updateWish = function(wish) {
var defer = $q.defer();
if (wish.image) {
// Rename temporary image.public_id to wish_id
cloudinaryService.renameImage(wish.image.public_id, wish._id,
function (image) {
// Update wish with renamed image
wish.image = image;
$http.put(URLS.WISH + "/" + wish._id, wish).success(function (wish) {
updateWishlist(wish);
defer.resolve(wish);
console.info("wish updated", wish);
});
});
} else {
$http.put(URLS.WISH + "/" + wish._id, wish).success(function (wish) {
updateWishlist(wish);
defer.resolve(wish);
console.info("wish updated", wish);
});
}
return defer.promise;
}
重构后的代码
model.updateWish = function(wish) {
var defer = $q.defer();
var renamedImagePromise = null;
if (wish.image) {
// Rename temporary image.public_id to wish_id
renamedImagePromise = cloudinaryService.renameImage(wish.image.public_id, wish._id)
.then( function (image) {
// Update wish with renamed image
wish.image = image;
return wish;
});
}
// Wait until renameImagePromise is resolved and send updated wish to server
$q.all([renamedImagePromise]).then(function(wishWithRenamedImage){
if (wishWithRenamedImage[0]) { // $q.all returns an array, wish is in "wishWithRenamedImage[0]"
wish = wishWithRenamedImage[0];
}
$http.put(URLS.WISH + "/" + wish._id, wish).success(function (wish) {
updateWishlist(wish);
defer.resolve(wish);
console.info("wish updated", wish);
});
})
return defer.promise;
}
这两个功能都有效,但我想知道这是否是满足我要求的最佳实现...
【问题讨论】: