search

Home  >  Q&A  >  body text

angular.js - angualrjs, how to write the next step after the $http asynchronous operation is executed

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

大家讲道理大家讲道理2801 days ago831

reply all(3)I'll reply

  • 天蓬老师

    天蓬老师2017-05-15 17:07:30

    Use events. Don’t use nesting

    $scope.$on('step1success',function(){
        //步骤二代码
    //执行完成后在回调函数中触发
        $scope.$emit('step2success');
    });
    $scope.$on('step2success',function(){
        //步骤3代码
    //执行完成后在回调函数中触发
        $scope.$emit('step3success');
    });
    $scope.$on('step3success',function(){
        //全部执行完成
    });
    
    //步骤一代码
    //执行完成后在回调函数中触发
    $scope.$emit('step1success');

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-15 17:07:30

    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对象,当所有promise对象成功返回时,$q.all().then()中的成功方法才会被执行。
    
    //  $http返回的正是promise对象

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-15 17:07:30

    The author can learn about $q and promise objects. As shown above, Angular has $q.all(), which you can use.

    reply
    0
  • Cancelreply