ajax – AngularJS – 对$q.all()的失败恢复
发布时间:2020-12-16 03:09:11 所属栏目:百科 来源:网络整理
导读:我正在尝试填补一些解决一系列远程调用的本地数据。 当每个承诺得到解决时,我加载数据并继续。 方法$ q.all([])正是这样做的: $q.all([ this.getUserInfo(11) .then(function (r) { results.push(r) }),this.getUserConns() .then(function (r) { results.
我正在尝试填补一些解决一系列远程调用的本地数据。
当每个承诺得到解决时,我加载数据并继续。 方法$ q.all([])正是这样做的: $q.all([ this.getUserInfo(11) .then(function (r) { results.push(r) }),this.getUserConns() .then(function (r) { results.push(r) }),this.getUserCtxs() .then(function (r) { results.push(r) }) ]) .then(function () { console.log(results) }) 问题是,这段代码没有弹性。 将调用包装在try / catch语句中,简单地导致$ q.all()完全忽略该条目,即使没有失败(请注意func中的console.log)… $q.all([ this.getUserInfo2(11) .then(function (r) { results.push(r) }),function () { try { this.getUserGroups() .then(function (r) { console.log(r) results.push(r) }) } catch (err) { console.log(err) } },]) .then(function () { console.log(results) }) 输出:
这将工作,但也将错误推送到阵列。
function push(r) { results.push(r); } $q.all([ this.getUserInfo(11).then(push).catch(push),this.getUserConns().then(push).catch(push),this.getUserCtxs().then(push).catch(push) ]) .then(function () { console.log(results); }) 你也应该提高你对承诺的理解,你永远不应该使用try-catch的承诺 – 当使用promises,你使用.catch()方法(其他一切都是隐含的尝试)。这适用于正常错误以及异步错误。 如果你想完全忽略错误: function push(r) { results.push(r); } function noop() {} $q.all([ this.getUserInfo(11).then(push).catch(noop),this.getUserConns().then(push).catch(noop),this.getUserCtxs().then(push).catch(noop) ]) .then(function () { console.log(results); }) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |