Unable to exit the function after ‘window.alert’ in Angular9

Tags: , , , ,



I am trying to calculate time difference and if time difference is greater than 20 mins, I want to display an alert message and then exit. I don’t intend to loop through all the rows and want to exit the function after finding out the first host which has minutes < 20.

    this.dataSource.filteredData.forEach(
        async row => {
            this.selection.select(row);
            // const host = row.hostName.substring(0, row.hostName.indexOf('.'));
            const host = 'abc';
            const prevData = await this.myService.getData(host);
            const timeDiff = Math.abs(new Date().getTime() - new Date(prevData[0].dateAt).getTime());
            const minutes = Math.floor((timeDiff / 1000) / 60);
            if (minutes < 20) {
                window.alert('Please check after ' + (20 - minutes) + ' minutes.');
                return false;
            }
        });

I am trying to exit the function using return false but it is still looping through all the rows.

Updated code without foreach:

    const f = (async row => {
        const host = 'abc';
        const prevData = this.myService.getData(host);
            const timeDiff = Math.abs(new Date().getTime() - new Date(prevData[0].dateAt).getTime());
            const minutes = Math.floor((timeDiff / 1000) / 60);
        return minutes;
    });

    (async () => {
        for (let i = 0; i < this.dataSource.filteredData.length; i++) {
            const mins = await f(this.dataSource.filteredData[i]);
            if (mins < 200) {
                window.alert('Please retry after ' + (200 - mins) + ' minutes.');
                break;
            }
        }
    })();

In the above code, this.myService.getData(host) is returning null

Answer

Here is a minimally-viable representation of how the control should be programmed:

let rows = [1, 2, 3];

let f = (async row => {
  return row === "2";
});

(async () => {
  for (let i = 0; i < rows.length; i++) {
    let result = await f(rows[i]);
    console.log(result);
    if (!result)  {
      break;
    }
  }
})();


Source: stackoverflow