如果第一个失败,则承诺 returns 第二个承诺结果
Promise that returns second promise result if first fails
如果第一个(缓存中的值)失败,我想 return 第二个承诺的值。
我有下面的代码,但是没有定义resolve。
exports.getConfig = function (a, r) {
return new Promise(resolve, reject) {
getConfigFromCache(a, r)
.catch(function(e){
getRouteConfigFromWeb(a, r)
}).then(function(result) {
//return value of the promise that was called
resolve(result)
})
}
};
假设 getConfigFromCache 和 getRouteConfigFromWeb return 都正确承诺。
有没有办法做到这一点,还是我想的不对?
您根本不需要创建新的 Promise
:
exports.getConfig = function (a, r) {
var cache = getConfigFromCache(a, r);
return cache.catch(function(e) {
return getRouteConfigFromWeb(a, r); // NB: return *essential*
});
}
如果 getConfigFromCache()
调用成功,生成的解析 Promise 应该跳过 .catch
并直接返回。
如果缓存调用失败,则返回从 getRouteConfigFromWeb()
返回的 Promise。
我还注意到,您问题的第一行实际上给出了解决方案:"I would like to return the value of a second promise if the first (value in cache) fails." - 您实际上从未在 .catch
阻止!
如果第一个(缓存中的值)失败,我想 return 第二个承诺的值。
我有下面的代码,但是没有定义resolve。
exports.getConfig = function (a, r) {
return new Promise(resolve, reject) {
getConfigFromCache(a, r)
.catch(function(e){
getRouteConfigFromWeb(a, r)
}).then(function(result) {
//return value of the promise that was called
resolve(result)
})
}
};
假设 getConfigFromCache 和 getRouteConfigFromWeb return 都正确承诺。
有没有办法做到这一点,还是我想的不对?
您根本不需要创建新的 Promise
:
exports.getConfig = function (a, r) {
var cache = getConfigFromCache(a, r);
return cache.catch(function(e) {
return getRouteConfigFromWeb(a, r); // NB: return *essential*
});
}
如果 getConfigFromCache()
调用成功,生成的解析 Promise 应该跳过 .catch
并直接返回。
如果缓存调用失败,则返回从 getRouteConfigFromWeb()
返回的 Promise。
我还注意到,您问题的第一行实际上给出了解决方案:"I would like to return the value of a second promise if the first (value in cache) fails." - 您实际上从未在 .catch
阻止!