0

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)
        .catch(function(e){
            getRouteConfigFromWeb(a, r)
        }).then(function(result) {
            //return value of the promise that was called
            resolve(result)
        })
  }
};

Assume that both getConfigFromCache and getRouteConfigFromWeb return promises correctly.

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

Tony Laidig
  • 1,048
  • 2
  • 11
  • 33

1 Answers1

3

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.

I note also that the very first line of your question actually gives the solution: "I would like to return the value of a second promise if the first (value in cache) fails." - you never actually put a return in the .catch block!

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • That is correct. The promise was passed through after all. – Tony Laidig Apr 27 '16 at 21:46
  • @user1886721 the key thing you were missing in your original code was the `return` inside the `.catch` block. Without it, the Promise chain is broken. – Alnitak Apr 27 '16 at 21:47