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 the nth
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?
You could wrap each iteration in a Promise and await it:
async function someMethod() {
for (var i = 0; i < 5; i++) {
await new Promise(resolve => {
setTimeout(()=> {
console.log('This is iteration ' + i);
resolve();
}, 500);
});
}
console.log ('print me only after all iterations');
}
someMethod();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With