JSFiddle - React, Tailwind, and code Playground
Image verification
by tonytlwu
JavaScript
function loadJSON () {
var url = 'https://api.themoviedb.org/3/search/movie';
var options = {
url: url,
dataType: 'json',
data: {
query: 'Batman',
api_key: '5fbddf6b517048e25bc3ac1bbeafb919'
}
};
console.clear();
return $.ajax(options)
}
function verifyImages (data) {
var totalLength = data.results.length;
var verifiedCount = 0;
var validUrls = [];
return new Promise(function (resolve, reject) {
$.each(data.results, function (i, image) {
var url = 'https://image.tmdb.org/t/p/w92' + image.poster_path;
if (i % 3 === 1) {
// Simulate bad URLs
url += '_';
}
var img = new Image();
img.onload = function(){
console.log(verifiedCount+1, 'LOADED');
validUrls.push(this.src);
if (++verifiedCount === totalLength) {
resolve(validUrls);
}
};
img.onerror = function(){
console.log(verifiedCount+1, 'ERROR');
if (++verifiedCount === totalLength) {
resolve(validUrls);
}
};
img.src = url;
});
});
}
loadJSON()
.then(function (data) {
console.log('Verifying...');
return verifyImages(data);
})
.then(function (images) {
console.log('Verified.');
$.each(images, function (i, image) {
$('body').append('<img src="'+image+'">');
});
});