Sequential code execution in angular/ typescript

后端 未结 7 2212
醉梦人生
醉梦人生 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:09

    Are you looking for something like this? (plunker)

    export class App {
      name:string;
      constructor() {
        this.name = `Angular! v${VERSION.full}`;
    
        this.someMethod();
      }
    
      doTimeout(currentIndex:int){
        return new Promise(resolve => {
          setTimeout(()=> {
            console.log("This is iteration " + currentIndex);
            resolve();
          },500);
        });
      }
    
      async someMethod() {
        for(let i=0;i<5;i++){
          await this.doTimeout(i);
        }
        // I want to execute this line of code only after the 
        // for loop has completed all iterations. 
        console.log ('print me only after all iterations'); 
    
        // ....
        // some more lines of code
      }
    }
    

    Sources: What is the JavaScipt Version of sleep? and Combination of async function + await + setTimeout

提交回复
热议问题