AngularJS:这是链接承诺的正确方法吗?
AngularJS : Is this the correct way to chain promises?
我有一个函数foo调用另一个函数moreFoo,我想在承诺中包装函数调用,以便foo返回的承诺在moreFoo解决后返回。下面是我的解决方案:
function foo() {
var defer = $q.defer();
console.log('doing foo');
moreFoo().then(defer.resolve);
return defer.promise;
}
function moreFoo() {
var defer = $q.defer();
setTimeout(function() {
console.log('doing more foo');
defer.resolve();
}, 2000);
return defer.promise;
}
foo().then(function() {
console.log('finished with all foos');
});
然后输出:
doing foo doing more foo finished with all foos
它似乎正在正常工作。这是拴住这些承诺的正确/最好的方法吗?
我不知道"最佳",但这可以通过利用$timeout
的承诺来简化很多…
function foo() {
console.log('doing foo');
return moreFoo();
}
function moreFoo() {
return $timeout(function() {
console.log('doing more foo');
}, 2000);
}
foo().then(function() {
console.log('finished with all foos');
});
我喜欢这样($timeout返回承诺):
function foo() {
return $timeout(function(){
console.log('doing foo');
},2000);
}
function moreFoo() {
return $timeout(function(){
console.log('doing more foo');
},2000);
}
foo()
.then(moreFoo)
.then(function(){
console.log('all foos done');
}, function() {
console.log('something went wrong');
});
这个例子展示了两个链接在一起的承诺。只有在第一个执行成功后,第二个才会执行。如果其中一个失败,则调用最后一个错误处理程序。
可以同时运行,甚至不需要使用$q.all()
链接它们
$q.all([ foo(), moreFoo()]).then(function(data){
console.log(data) /* array of responses from all resolved promises */
});
很好的参考:https://egghead.io/lessons/angularjs-q-all
相关文章:
- 打破承诺链的好方法是什么
- 将同步函数包装到承诺中的最佳方法是什么?
- “未捕获(在承诺中)”在获取“then”方法中调用拒绝函数时
- 如何实现这种方法与承诺
- 有没有一个好的方法来缩短Javascript的承诺
- 这是使用承诺与 Sequelize.js的正确方法吗?
- jasmine 2.0测试angularjs的工厂方法,这是一个承诺
- 是否可以覆盖本机 Es6 承诺解析方法
- 在nodejs中使用Q.js承诺进行循环的正确方法
- 将承诺处理程序绑定到其类的更好方法
- 使用取消方法增强ES6承诺
- 承诺取消方法.为什么它还没有实现,而不是其他承诺框架
- 猫鼬静态方法返回蓝鸟承诺
- 如何承诺一个节点.js插件方法
- 问.js节点承诺.“套接字”上缺少错误处理程序.类型错误:无法调用未定义的方法“then”
- 有没有一种 AngularJS 方法来使用带有承诺返回的浏览器模式
- 如何在返回承诺的服务中创建 reset() 方法
- 使用承诺作为数据依赖项的正确方法
- 使用承诺编写可读代码的最佳方法是什么?
- 为什么在Lightswitch中堆叠承诺的一种方法有效,而另一种方法则不起作用