代码之家  ›  专栏  ›  技术社区  ›  Thunfische

在angularjs中执行另一个请求之前,请等待请求完成

  •  0
  • Thunfische  · 技术社区  · 7 年前
        A.Add1()
            .success(function (response) {
                alert("add1");
            }).
            error(function (response) {
                alert("error in add1");
            });
    
    
    
        A.Add2()
            .success(function (response) {
                alert("add2");
            }).
            error(function (response) {
                alert("error in add2");
            });
    

    我需要一个接一个地处理两个请求。但有时第二种方法是在第一种方法之前进行的。我如何在angularjs中防止这种情况?

    2 回复  |  直到 7 年前
        1
  •  2
  •   Khai Kiong    7 年前

    为了方便起见,您可以执行 A.Add2() 成功函数的内部 A.Add1()

    示例如下:

        A.Add1()
            .success(function (response) {
                alert("add1");
    
                A.Add2()
                .success(function (response) {
                    alert("add2");
                }).
                error(function (response) {
                    alert("error in add2");
                });
            }).
            error(function (response) {
                alert("error in add1");
            });
    
        2
  •  1
  •   Shashank Vivek    7 年前

    尝试

       A.Add1()
        .success(function (response) {
            alert("add1");
            A.Add2().success(function (response) {
                alert("add2");
              }).
               error(function (response) {
                alert("error in add2");
               });
          }).
        error(function (response) {
            alert("error in add1");
        });
    

    嵌套承诺

    附言: .success 不推荐使用。更喜欢 .then()