更改在打字稿中使用Promise.all的方法

时间:2016-10-20 15:19:38

标签: javascript typescript promise protractor rxjs

我有以下方法:

public static zoomInMap(times: number): void {

  for (let i = 0; i < times; i++) {
    let zoomInButton = element(by.css('#main > cc-map > div.google-map-base-  container-inner > div > div.gmnoprint.gm-bundled-control.gm-bundled-control-on-bottom > div:nth-child(1) > div > div:nth-child(1)'));
    zoomInButton.click();
    browser.sleep(Config.ZOOM_ANIMATION_TIMEOUT).then(() => {
    // console.log('Map Zoomed In');
   });
 }

}

我想让它返回一个Promise。我想使用Promise.all 像:

 public static zoomInMap(times: number): Promise<any> {

 return Promise.all( ? ) // ? I do not know how to do it
  for (let i = 0; i < times; i++) {
    let zoomInButton = element(by.css('#main > cc-map > div.google-map-base-container-inner > div > div.gmnoprint.gm-bundled-control.gm-bundled-control-on-bottom > div:nth-child(1) > div > div:nth-child(1)'));
    zoomInButton.click();
    browser.sleep(Config.ZOOM_ANIMATION_TIMEOUT).then(() => {
     // console.log('Map Zoomed In');
    });
  }
}

我应该如何重做代码以使用Promise.all。抱歉蹩脚的问题。

2 个答案:

答案 0 :(得分:2)

在数组中收集你的promises,然后在数组上调用Promise.all并返回结果,这是聚合的承诺:

public static zoomInMap(times: number): Promise {
  let promises = [];
  for (let i = 0; i < times; i++) {
    let zoomInButton = element(by.css('#main > cc-map > div.google-map-base-  container-inner > div > div.gmnoprint.gm-bundled-control.gm-bundled-control-on-bottom > div:nth-child(1) > div > div:nth-child(1)'));
    zoomInButton.click();
    promises.push(browser.sleep(Config.ZOOM_ANIMATION_TIMEOUT).then(() => {
        // You can do something here if you like, or remove the `then`
    }));
  }
  return Promise.all(promises);
}

我对TypeScript不大,你可能需要调整数组的声明。我已将函数的返回类型从void更改为Promise

答案 1 :(得分:1)

您可以创建大小为Array的{​​{1}},而不是使用循环。然后用times填充它:

map