How to break/cancel forEach loop inside async with timeout

Viewed 229

I have an array like [1,2,3,4,5,6,7,8,9,10]. I want to run forEach of this array, each item have timeout 1s and if current item match the condition then break the foreach. i found the code that worked with out async only:

var BreakException = {};

try {
  [1,2,3,4,5,6,7,8,9,10].forEach(function(el) {
    console.log(el);
    if (el === 6) throw BreakException;
  });
} catch (e) {
  if (e !== BreakException) throw e;
}

But when i use async, it run all item:

var BreakException = {};
let list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var realtimePromise = new Promise((resolve, reject) => {
  list.every(async(item, pKey) => {
    await setTimeout(function() {
      try {
        console.log(item);
        if (item === 6) throw BreakException;
      } catch (e) {
        if (e !== BreakException) throw e;
      }
    }, 2000 * pKey);
  });
});
realtimePromise.then(() => {
  console.log('------- End loop -------');
});

Anyone have solution for this issue?

1 Answers

You would be better off with a recursive function like this, as exiting a forEach loop with an error is not a good practice:

const list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const realtimePromise = (index = 0) => {
    return new Promise((resolve, reject) => {
        if (index > list.length - 1) reject(new Error('Item not in list'));
        const currentItem = list[index];
        console.log(currentItem);
        if (currentItem === 6) resolve(currentItem);
        else setTimeout(() => {
            resolve(realtimePromise(++index));
        }, 2000);
    });
}

realtimePromise().then(() => {
    console.log('------- End loop -------');
});

Related