当一个 fetch url 给出 net::ERR_CONNECTION_REFUSED 错误时,用于获取任务的 Promise.race 将停止

问题描述 投票:0回答:1

当一个 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
javascript promise fetch-api
1个回答
0
投票
当一种成分被拒绝而另一种成分尚未沉淀时,

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");

© www.soinside.com 2019 - 2024. All rights reserved.