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 only after thenth
iteration has completed.I want the code after the loop to execute only after the for loop has completed all interactions.
Example code:
someMethod() {
for ( var i = 0; i < someLength; i++) {
// get some data
this.dataService.get(i).subscribe(data => {
// do something with the data
});
}
//
console.log ('print me only after all iterations');
// ....
// some more lines of code
}
Here is another example ( Plunker ) :
someMethod() {
for ( var i = 0; i < 5; i++) {
setTimeout(()=> {
console.log('This is iteration' + i);
},500);
}
// 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
}
Any ideas?