Faisal Faisal - 10 months ago 54
TypeScript Question

Synchronous code execution in angular/ typescript

How can I make my code run synchronously? For example,


  1. 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.

  2. 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?

Answer Source

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();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download