I have a list of urls I wish to fetch. All of these urls returns a json object with a property valid
. But only one of the fetch promises has the magic valid
property to true
.
I have tried various combinations of url.forEach(...)
and Promises.all([urls]).then(...)
. Currently my setup is:
const urls = [
'https://testurl.com',
'https://anotherurl.com',
'https://athirdurl.com' // This is the valid one
];
export function validate(key) {
var result;
urls.forEach(function (url) {
result = fetch(`${url}/${key}/validate`)
.then((response) => response.json())
.then((json) => {
if (json.license.valid) {
return json;
} else {
Promise.reject(json);
}
});
});
return result;
}
The above is not working because of the async promises. How can I iterate my urls and return when the first valid == true
is hit?