Sequential code execution in angular/ typescript

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

    You can do it with Promise.

    someMethod() : Promise {
    
     return new Promise((resolve) => {
      for ( var i = 0; i < someLength; i++) {
            // get some data
            this.dataService.get(i).subscribe(data => {
                // do something with the data
            }); 
    
    if(i==someLength-1){resolve();}
        }
    
    
    }).then(()=>{ 
    
    
        // 
        console.log ('print me only after all iterations');
    
        // ....
        // some more lines of code
    })
    }
    

提交回复
热议问题