Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequential code execution in angular/ typescript

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

like image 688
Faisal Avatar asked Jan 29 '23 19:01

Faisal


1 Answers

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();
like image 133
Cristi Mihai Avatar answered Feb 05 '23 16:02

Cristi Mihai