Iterate over array of WinJS Promises and break if one completed successful

白昼怎懂夜的黑 提交于 2019-12-11 06:39:40

问题


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)



来源:https://stackoverflow.com/questions/27424109/iterate-over-array-of-winjs-promises-and-break-if-one-completed-successful

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!