There are three steps
step1: $http.jsonp(url1)
step2: $http.jsonp(url2)
step3: assignment operation,
There is no order requirement for steps 1 and 2. 3 is required to be executed after steps 1 and 2 are completed;
Because steps 1 and 2 will be called in many places, we don’t want it to be
步驟1.success{
步驟2.success{
步驟3}} 這樣的寫法
I hope to encapsulate steps 1 and 2 into a public method, and then execute step 3 sequentially. How should I write it in angularjs
光陰似箭催人老,日月如移越少年。
Use events. Don’t use nesting
$scope.$on('step1success',function(){
//步驟二代碼
//執(zhí)行完成后在回調(diào)函數(shù)中觸發(fā)
$scope.$emit('step2success');
});
$scope.$on('step2success',function(){
//步驟3代碼
//執(zhí)行完成后在回調(diào)函數(shù)中觸發(fā)
$scope.$emit('step3success');
});
$scope.$on('step3success',function(){
//全部執(zhí)行完成
});
//步驟一代碼
//執(zhí)行完成后在回調(diào)函數(shù)中觸發(fā)
$scope.$emit('step1success');
Use the $q service that comes with ng
let promises = {
alpha: promiseAlpha(),
beta: promiseBeta(),
gamma: promiseGamma()
}
$q.all(promises).then((values) => {
console.log(values.alpha); // value alpha
console.log(values.beta); // value beta
console.log(values.gamma); // value gamma
complete();
});
// promises包含多個promise對象,當(dāng)所有promise對象成功返回時,$q.all().then()中的成功方法才會被執(zhí)行。
// $http返回的正是promise對象
The author can learn about $q and promise objects. As shown above, Angular has $q.all(), which you can use.