【发布时间】:2018-02-19 09:43:21
【问题描述】:
我正在一组 URL 中寻找最佳 URL(比如本地缓存): ['https://1.2.3.4', 'https://httpbin.org/delay/3', 'https://httpbin.org/status/500'] 并选择具有5 秒超时。否则回退到“https://httpbin.org/status/200”。在这个人为的例子中,'https://httpbin.org/delay/3' 应该获胜!
function fallback(response) {
if (response.ok) {
return response;
}
console.log("Trying fallback")
return fetch("https://httpstat.us/200") // absolute fallback
}
var p = Promise.race([
fetch('https://1.2.3.4'), // will fail
fetch('https://httpbin.org/delay/3'), // should be the winner
fetch('https://httpbin.org/status/500'), // will fail
new Promise(function(resolve, reject) { // Competing with a timeout
setTimeout(() => reject(new Error('request timeout')), 5000)
})
])
.then(fallback, fallback)
.then(console.log)
我的代码存在Promise race 在任何返回时结束的问题。我怎样才能最好地构建它,以便“https://httpbin.org/delay/3”正确地赢得比赛?
【问题讨论】:
-
当你说“将失败”时,你的意思是承诺拒绝吗?
-
不,除非服务器无法访问,否则承诺应该始终成功。发生的情况是服务器响应但状态不是 200,因此不是有效的端点。
标签: javascript promise fetch