user1886721 user1886721 - 1 year ago 63
Javascript Question

Promise that returns second promise result if first fails

I would like to return the value of a second promise if the first (value in cache) fails.

I have the following code, but resolve is not defined.

exports.getConfig = function (a, r) {
return new Promise(resolve, reject) {
getConfigFromCache(a, r)
getRouteConfigFromWeb(a, r)
}).then(function(result) {
//return value of the promise that was called

Assume that both getConfigFromCache and getRouteConfigFromWeb return promises correctly.

Is there a way to accomplish this, or am I thinking through it incorrectly?

Answer Source

You shouldn't need to create a new Promise at all:

exports.getConfig = function (a, r) {
    var cache = getConfigFromCache(a, r);
    return cache.catch(function(e) {
        return getRouteConfigFromWeb(a, r);  // NB: return *essential*

If the getConfigFromCache() call succeeds, the resulting resolved Promise should skip through the .catch and get returned directly.

If the cache call fails, the Promise returned from getRouteConfigFromWeb() is returned instead.