Search code examples
angularecmascript-6es6-promise

How to make synchronous chain call with Angular 2?


I have an action1 and action2 methods. action1 method creates a project structure and action2 method fills this structure with data. So first I need to call action1 and when it completes I need to call action2.

Is there any way to make synchronous chain call?

startPoint(){

    action1();
    action2();

}



action1(){
   //create a project structure
   return "completed";
}

action2(){
   //fill project structure with data
   return "completed";
}

Solution

  • To give you an example.

    action1() {
        return new Promise((resolve, reject) => {
            // do something
            resolve(<your return value>);
        });
    }
    action2() {
        // Do something
    }
    
    action1().then((res) => {
        action2();
    }).catch(() => {
        // error case when reject is called
    });
    

    Alternatively you could just return Promise.resolve(<value>); in action1 and you can also use the reject() method in your promise in case of an error.