遍历WinJS承诺的数组,并打破如果成功完成 [英] Iterate over array of WinJS Promises and break if one completed successful

查看:123
本文介绍了遍历WinJS承诺的数组,并打破如果成功完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个WinJS承诺,我想直到一个完成,没有一个错误顺序调用。

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

伪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.

推荐答案

基本上你想要

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

或(扁平化)

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());

(这是非常相似的 Promise.any ,除了它按顺序等待)

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

这篇关于遍历WinJS承诺的数组,并打破如果成功完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆