Thunfische
Thunfische

Reputation: 1157

Wait for a request to finish before doing another one in angularjs

    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");
        });

I need to do two requests one by one. But sometimes the second one is being done before the first one. How do I prevent this in angularjs?

Upvotes: 0

Views: 43

Answers (2)

Khai Kiong
Khai Kiong

Reputation: 461

For easier way, you can execute the A.Add2() inside of the success function A.Add1().

Example as below:

    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");
        });

Upvotes: 2

Shashank Vivek
Shashank Vivek

Reputation: 17514

Try

   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");
    });

Nested promise

PS: .success is deprecated. Prefer .then().

Upvotes: 1

Related Questions