有人可以帮我按顺序从youtube加载带有承诺的图像吗?:
maxresdefault
不存在,请等到数组(hqdefault
)中的下一张图片。谢谢:
这里是codepen example:
let noImageUrl = '';
const resolutions = ['maxresdefault', 'hqdefault', 'mqdefault', 'sddefault'];
let videoId = 'dQw4w9WgXcQ';
resolutions.forEach(item => {
let url = 'https://i.ytimg.com/vi/' + videoId + '/' + item + '.jpg';
loadImage(url)
.then((img) => {
console.log('img ', img);
document.body.append(img)
})
.catch(error => console.error('error ', error));
});
function loadImage(url) {
return new Promise((resolve, reject) => {
const img = new Image();
img.addEventListener('load', e => {
img.naturalWidth <= 240 ? reject(new Error('No image found')) : resolve(img);
});
img.addEventListener('error', () => {
reject(new Error(`Failed to load image's URL: ${url}`));
});
img.src = url;
});
}
答案 0 :(得分:1)
您可以使用.catch()
方法将多个promise链接在一起,作为一个回退机制。
此代码应能解决问题: https://codepen.io/anon/pen/rogRKR
let noImageUrl = '';
// this will work as intended
let defaultResolution = 'maxresdefault';
let fallbackResolutions = ['hqdefault', 'mqdefault', 'sddefault'];
// uncomment to simulate a fallback
// defaultResolution = 'i dont exist';
// fallbackResolutions = ['i dont exist either', 'mqdefault', 'sddefault'];
let videoId = 'dQw4w9WgXcQ';
let p = loadImage(videoId, defaultResolution);
fallbackResolutions.forEach(resolution => {
p = p.catch(err => loadImage(videoId, resolution))
});
p.then((img) => {console.log('img ', img); document.body.append(img)})
.catch(error => console.error('error ', error));
function loadImage(videoId, resolution){
let url = 'https://i.ytimg.com/vi/'+videoId+'/'+resolution+'.jpg';
return new Promise((resolve, reject) => {
const img = new Image();
img.addEventListener('load', e => {
img.naturalWidth <= 240 ? reject(new Error('No image found')) : resolve(img);
});
img.addEventListener('error', () => {
reject(new Error(`Failed to load image's URL: ${url}`));
});
img.src = url;
});
}