How to make Method process in sequence

17 views
Skip to first unread message

Sivaprakash Gopal

unread,
Jul 13, 2019, 12:57:55 AM7/13/19
to Angular and AngularJS discussion
Hi All,

I am new angular, how to make method processing as sequential. Based on api response, i need to navigate to different component.
In this case, how to make process sequential.


let responseObj = null;
let path = null;
buttonClick(){
method1();
router.navigateByURL(path);
}


method1(){
 responseObj =  api call();
 method2(responseObj);
}

method2(responseObj){
 path = processing - > responObj;
}

Thanks,
Siva

Tito

unread,
Jul 14, 2019, 9:18:06 PM7/14/19
to Angular and AngularJS discussion
Method1().then(method2())

Zlatko Đurić

unread,
Jul 15, 2019, 2:56:36 AM7/15/19
to Angular and AngularJS discussion
Hi Siva,

Your call to the method is sync, but the actual execution is async. Additionally, your method1 calls method2, which has what we call a side effect. (Setting that local path variable).

You can do several approaches here, e.g. use a promise, like Tito suggested:

    buttonClick() {
      method1()
          .then(() => {
              router.navigateByUrl(path);
           });

Of course, you also need to make method1 a promise that doesn't return until method2 with it's side effect is executed:

    method1() {
      return apiCall()
        .then(result => this.method2(result));
    }



Alternatively you can make your buttonClick an async function, then it might be easier to understand, so now (together with method1 change above), your buttonClick looks like this:

async buttonClick() {
    await method1();
    return router.navigateByUrl(path);
}

There are other ways to do this, but this should get you started.

Zlatko
Reply all
Reply to author
Forward
0 new messages