当一个url不可用时,我试图使用另一个url,但承诺的竞争是一个获取的连接错误拒绝了另一个获取过程。
在代码中,您可以看到
reverse
被注释的函数。取消注释时,竞争不会被拒绝。也许这是一个提示。如何改进代码以使用替代URL?(好的url与端口11112一致)
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="UTF-8">
<title>Home</title>
<meta content="width=device-width, initial-scale=1" name="viewport">
<link href="" rel="stylesheet" title="style">
<script>
(() => {
let urls = [
'http://localhost:11997/style.css',
'http://localhost:11112/style.css'
]
// urls = urls.reverse();
console.log(urls);
let i = 0, promises = [];
while (urls.length) {
const url=urls.shift();
console.log(url);
promises.push(fetch(url, {method: 'HEAD'}));
}
p = Promise.race(promises);
console.log(p);
p
.then(response => {
console.log(response.url);
return response.url;
})
.then(res_data => {
document.querySelector('[title=style]').href = res_data;
})
p
.catch(e => console.log('trzczy', e))
})();
</script>
</head>
<body>
content
</body>
</html>
错误
(2)Â ['http://localhost:11997/style.css', 'http://localhost:11112/style.css']
index.html:19 http://localhost:11997/style.css
index.html:19 http://localhost:11112/style.css
index.html:23 Promise {<pending>}
index.html:20
HEAD http://localhost:11997/style.css net::ERR_CONNECTION_REFUSED
(anonymous) @ index.html:20
(anonymous) @ index.html:34
index.html:33 trzczy TypeError: Failed to fetch
at index.html:20:31
at index.html:34:11
index.html:20
Uncaught (in promise) TypeError: Failed to fetch
at index.html:20:31
at index.html:34:11
(anonymous) @ index.html:20
(anonymous) @ index.html:34
Promise.then (async)
(anonymous) @ index.html:29
(anonymous) @ index.html:34