假设我有 2 个 http 请求,我希望异步调用这两个请求,但我希望在渲染 View 之前完成这两个请求,我如何条件完成 2 个单独的调用才能调用一个函数。 call3 和 call4 仍在后台运行,但我不想等待它们完成。
我添加了示例代码:
var call1_done = false;
var call2_done = false;
var call3_done = false;
var call4_done = false;
API.get_client().then(function(){
call1_done = true;
});
API.get_all_clients().then(function(){
call2_done = true;
});
// ignore call3 and call4 they can continue in the background
if (call1_done && call2_done)
{
render_the_page();
}
最佳答案
如果您对使用 $q.all([])
不感兴趣,我会尝试使用 $watch
。
$scope.calls = {
call1_done: false,
call2_done: false
};
API.get_client().then(function(){
$scope.calls.call1_done = true;
});
API.get_all_clients().then(function(){
$scope.calls.call2_done = true;
});
/* 2 and 4 async tasks are running ..... */
$scope.$watch(function () {
return $scope.calls;
},
function (newValue, oldValue) {
if(newValue.call1_done && newValue.call2_done ){
render_the_page();
}
}, true);
这里我们监听一个存储两个标志的对象,如果两个标志都变为true
-> 触发render_the_page()
关于javascript - AngularJs 在完成 2 个不同的 https 请求时调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20846995/