Я бы хотел отделить выборку списка URL-адресов от того, как вы его обрабатываете (например, ваш Object.assign
вызов.)
В этой версии fetchFirstWorking
принимает список URL-адресов и отвечает:Обещание, которое будет выполнено в результате получения первого живого URL.Обратите внимание, что он использует рекурсию, а не счетчик, поэтому управление состоянием сведено к минимуму.
getConfiguration
содержит бизнес-логику.
const fetchFirstWorking = ( [url, ...urls], conf ) => url
? fetch (url, conf)
.catch ( _ => fetchFirstWorking (urls) )
: Promise .reject ('no urls could be loaded')
const getConfigurations = (urls) =>
fetchFirstWorking(urls)
.then ( res => res .json () )
.then ( res => Object .assign ({a: 'test'}, res) )
const urls = [
'https://dewnuf111111.com/configuration',
'https://dewnuf222222.com/configuration',
'https://bcsmania.co.uk/test.json'
]
getConfigurations (urls)
.then(console.log)
.catch(console.warn)
Если вы замените последний URL другим фиктивным, вместо этого вы увидите предупреждение консоли:
const fetchFirstWorking = ( [url, ...urls], conf ) => url
? fetch (url, conf)
.catch ( _ => fetchFirstWorking(urls) )
: Promise .reject ('no urls could be loaded')
const getConfigurations = (urls) =>
fetchFirstWorking(urls)
.then ( res => res .json () )
.then ( res => Object .assign ({a: 'test'}, res) )
const urls = [
'https://dewnuf111111.com/configuration',
'https://dewnuf222222.com/configuration',
'https://dewnuf333333.com/configuration',
]
getConfigurations (urls)
.then(console.log)
.catch(console.warn)