Iterate over array of WinJS Promises and break if

2019-08-10 08:22发布

问题:

I have 3 WinJS Promises that I want to call sequentially until one completes without an error.

Pseudo code:

var promises = [promise1,promise2,promise3];
promises.each (promise)
  promise.then (result) return result

Of course, I cannot use .each on the array as this would execute the promises in parallel.

So first the iteration should be sequential and if the promise returns with an error the next promise should be tried, otherwise it should return the value of the successful promise. If no promise returns successful, then the whole loop should indicate a failure.

回答1:

Basically you want

return promise1.catch(function(err) {
    return promise2.catch(function(err) {
        return promise3;
    });
})

or (flattened)

makePromise1().catch(makePromise2).catch(makePromise3);

You can easily create this chain dynamically from an array of to-be-tried functions by using reduce:

return promiseMakers.reduce(function(p, makeNext) {
    return p.then(null, makeNext);
}, WinJS.Promise.wrapError());

or if you really have an array of promises (tasks that were already started to run in parallel):

return promises.reduce(function(p, next) {
    return p.then(null, function(err) {
        return next;
    });
}, WinJS.Promise.wrapError());

(which is very similar to Promise.any, except that it waits sequentially)