How to repeat the same Promise in NodeJS with an Array input until it resolves or the Array ends?

I have an array of URLs for the same audio file which are not always working due to server loads. So, whenever a URL is needed, I should check first the headers of the first URL to make sure it’s working now. If it’s not working, I check the next URL.. and so on until the array ends.

My question is: How to chain a recurring of the same Promise (different URL each time) with the ability to break the chain once a working URL is found?

Answer

I managed to get it working as following:

function audioPicker(audioUrlArray, i){
    return new Promise((resolve, reject) =>{
        audioUrlCheck(audioUrlArray[i])
            .then(isAvailable =>{
                if(isAvailable) resolve(audioUrlArray[i])
                else if (i+1 < audioUrlArray.length){
                    audioPicker(audioUrlArray, i+1)
                    .then(pick => resolve(pick))
                    .catch(e => reject(e))
                } else reject ('All audio files are not available.')
            })
            .catch(e => log("AuidoPicker Error: ", e)) // Don't reject here
    })
}
    
    
function audioUrlCheck(url){
    return new Promise((resolve, reject) =>{
        axios.head(url) // Using axios as "fetch" is not built-in in NodeJS
        .then(r =>{
            log('Fetched audio file URL headers.')
            if(r.headers['content-type'] == 'audio/mpeg') resolve(true)
            else resolve(false)
        })
        .catch(e => resolve(false)) // No reject if Url request failed
    })
}

audioPicker (urlArray, 0)
    .then(pick => resolve(pick))
    .catch(e => reject(e))