Sequential code execution in angular/ typescript

后端 未结 7 2157
醉梦人生
醉梦人生 2021-01-01 06:02

How can I make my code run sequentially? For example,

  1. If I have a for loop which gets some data from a service, I want the n+1 iteration to run

7条回答
  •  离开以前
    2021-01-01 06:14

    As Javascript is a single thread language, it is hard to do what exactly you want to achieve unless you use Promise or other callback architecture.

    There are many ways to achieve it through PROMISEs. Here, I'll show you how can you achieve the same using advance JavaScript concept called Async & Await in Angular framework.

    Please note there are many ways with Promise but my intention is to introduce you to new async & await concept where you don't need to chain the callback for success and reject methods.

    DEMO : https://plnkr.co/edit/16k66yRjXLPwTM50kYNS

    export class App {
      name:string;
      constructor() {
        this.name = `Angular! v${VERSION.full}`;
        this.someMethod(); 
      }
    
     const someMethod_Promise = () => {
      return new Promise((resolve,reject)=>{
         for ( var i = 0; i < 5; i++) {
           console.log('printing value of i ' + i);
            if(i==4)   // real condition
             resolve(true);
         } 
      })
     }
    
     const someMethod = async()=>{
       let result= await this.someMethod_Promise();
       if(result){
          console.log ('print me only after all iterations'); 
       }
     }
    }
    

提交回复
热议问题