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?