在JavaScript中遍历URL数组,返回首个可访问URL的索引
遍历URL数组找到首个可访问URL的索引解决方案
你的ping函数已经能通过Promise返回URL的可访问状态,要实现"找到首个可访问URL就停止遍历并返回索引"的需求,最直接的方式是用async/await配合普通for循环——因为在async函数中,await会阻塞循环等待Promise完成,这时可以正常终止循环并返回结果。
核心实现代码
async function findFirstAccessibleUrlIndex(urls: string[]): Promise<number | null> { for (let index = 0; index < urls.length; index++) { const isAccessible = await this.ping(urls[index]); if (isAccessible) { return index; // 找到首个可访问URL,直接返回索引并终止函数 } } return null; // 所有URL都不可访问时返回null }
为什么这个方法能解决你的问题?
- 普通for循环(而非forEach/map这类迭代器)支持在async函数中配合await使用,每次迭代都会等待
ping的Promise执行完成后再进入下一次循环。 - 一旦检测到可访问的URL,直接返回当前索引,循环和函数会立即终止,不会继续遍历后续URL,完全符合你"找到首个就停止"的需求。
对原ping函数的类型优化(可选)
原函数的Promise返回值可以明确标注为boolean,让类型更严谨:
function ping(url: string): Promise<boolean> { return new Promise((resolve) => { this.http.get(url, { observe: 'response' }).subscribe( (response) => { resolve(response.status === 200); }, (error) => { resolve(false); } ); }); }
使用示例
调用这个async函数时,需要用await或.then处理返回的Promise:
// 在async函数内调用 async function checkUrls() { const urls = ['https://example.com', 'https://test.com', 'https://demo.com']; const firstValidIndex = await this.findFirstAccessibleUrlIndex(urls); if (firstValidIndex !== null) { console.log(`首个可访问URL的索引:${firstValidIndex}`); } else { console.log('所有URL均无法访问'); } } // 或用链式调用 this.findFirstAccessibleUrlIndex(urls) .then(index => { index !== null ? console.log(`首个可访问URL的索引:${index}`) : console.log('所有URL均无法访问'); });
内容的提问来源于stack exchange,提问作者MWInCO
相关产品推荐
相关产品推荐

