角同步For循环

时间:2018-11-16 20:13:46

标签: angular typescript

角度5 中,如何以同步方式执行For循环。到目前为止,我没有下面的代码,这些代码不会等到ExcecuteAsyncCode完成。

let items = new Array<Item>();

for (let i = 0; i <= 10000; i += 1) {

    this.ExcecuteAsyncCode(i).then(
    res => {
        let result = res;
        return result;
    }).then(response => {
        let temp = response as Item[];
        temp.forEach((cta: Item) => {   
          items.push(cta);
        });
    });

    // THIS EXCECUTED BEFORE ExcecuteAsyncCode PROMISE COMPLETED
    if (items.length < i) {
        return;
    }
}

2 个答案:

答案 0 :(得分:2)

无法同步等待异步操作完成,并且即使您这样做也可能会阻塞浏览器UI,您也不想这样做。

您可以将then调用链接在一起,也可以使用async /await

来更异步地查看异步代码
interface Item{
    id:number
}
class Test{
    async ExecuteAsyncCode(i:number) {
        return [] as Item[]
    }
    async method() {
        let items = new Array<Item>();

        for (let i = 0; i <= 10000; i += 1) {

            let temp = await this.ExecuteAsyncCode(i);
            temp.forEach((cta: Item) => {
                items.push(cta);
            });

            if (items.length < i) {
                return;
            }

        }
    }
}

例如,您可以阅读有关异步/ await here的更多信息,值得一提的是,它不是Typescript独有的,Javascript也正在异步等待

答案 1 :(得分:1)

编辑:您不能简单地将同步(for循环)与异步混合使用。这种方法无需使用for循环,但应该能够解决您要从问题中实现的目标。

export class AppComponent {

  ngOnInit() {
    this.method();
  }

  i: number = 0;

  // let's say async will exit after this.i reached 5
  items = 5;//new Array<Item>(); 

  method() {
    this.asyncMethod().then((result) => {
      if (this.i > 10) return;

      if (result === 'exit') { // break the async recursive call
        return;
      }
      else {
        this.i += 1;
        this.method(); // do recursive call while this.i <= 10000 and items.length < this.i
      }
    });
  }

  asyncMethod() {
    return new Promise((resolve) => {
      let currLoop = new Promise((resolve, reject) => {
        // mimic async function using timeout
        // replace your async function here, don't forget to indicate resolve() when function is done
        setTimeout(() => {
          resolve();
        }, 3000);
      }).then(() => {
        // exit condition
        if (this.items < this.i) {
          resolve('exit');
        } else {
          resolve('done');
        }
      });
    });
  }
}