在angular/打字稿中顺序执行代码 [英] Sequential code execution in angular/ typescript

查看:50
本文介绍了在angular/打字稿中顺序执行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

  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.

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

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
}

这是另一个示例( 柱塞 ):

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
}

有什么想法吗?

推荐答案

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

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();

这篇关于在angular/打字稿中顺序执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆