angular/typescript中的顺序代码执行

Fai*_*sal 2 typescript angular

如何让我的代码按顺序运行?例如,

  1. 如果我有一个for循环从服务获取一些数据,我希望n+1迭代只在nth迭代完成后运行.

  2. 我希望循环之后的代码只有在for循环完成所有交互之后才能执行.

示例代码:

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
}
Run Code Online (Sandbox Code Playgroud)

这是另一个例子(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
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Cri*_*hai 7

您可以将每个迭代包装在Promise中并等待它:

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();
Run Code Online (Sandbox Code Playgroud)