如何在有超时的情况下中断/取消async内部的每个循环



我有一个类似[1,2,3,4,5,6,7,8,9,10]的数组。我想运行这个数组中的每个,每个项目都有超时1s,如果当前项目符合条件,则中断forEach。我找到了只适用于out-async的代码:

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

但当我使用async时,它会运行所有项目:

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

有人能解决这个问题吗?

您最好使用这样的递归函数,因为带错误退出forEach循环不是一个好做法:

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

最新更新