如何解决如何使用超时打破/取消forEach循环
我有一个像[1,2,3,4,5,6,7,8,9,10]的数组。我想运行此数组的forEach,每个项目都有超时1s,如果当前项目与条件匹配,则中断foreach。 我找到了仅与异步兼容的代码:
var BreakException = {};
try {
[1,10].forEach(function(el) {
console.log(el);
if (el === 6) throw BreakException;
});
} catch (e) {
if (e !== BreakException) throw e;
}
但是当我使用异步时,它将运行所有项目:
var BreakException = {};
let list = [1,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 -------');
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。