How can I make my code run sequentially? For example,
If I have a for loop which gets some data from a service, I want the n+1 iteration to run
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