当一个 url 不可用时,我尝试使用替代 url,但承诺的竞争是一个 fetch 的连接错误拒绝了另一个 fetch 的过程。
在代码中你可以看到被注释的
reverse
函数。当它未被注释时,竞赛不会被拒绝。也许这是一个提示。如何改进代码以使用替代网址? (好的网址是端口 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
Promise.race
会被拒绝。请改用 Promise.any
,因为当一种成分满足时,即使另一种成分已被拒绝,它也满足。另请参阅此处。
function twoRequests() {
return [
fetch("https://httpbin.org/delay/1"),
fetch("https://does.not.exist")
];
}
function logPromise(p, title) {
p.then(function(value) {
console.log(title, "fulfilled with value", value);
}, function(err) {
console.error(title, "rejected with error", err);
});
}
logPromise(Promise.race(twoRequests()), "race");
logPromise(Promise.any(twoRequests()), "any");