Jerzy Gruszka Jerzy Gruszka - 1 month ago 9
Javascript Question

Change method to use Promise.all in typescript

I have following method:

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');
});
}


}

I want to make it return a Promise . I want to use Promise.all
Like:

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');
});
}
}


How should I rework the code to use Promise.all . Sorry for lame question.

Answer

Gather up your promises in an array, then call Promise.all on the array and return the result, which is the aggregated promise:

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

I'm not big on TypeScript, you may have to adjust the declaration of the array. I've changed the return type of the function from void to Promise.