Created
February 11, 2021 11:05
-
-
Save belocer/c5094a858ae896b8437b35625f0ba6f2 to your computer and use it in GitHub Desktop.
Обработка ошибок в Promise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Promise Error</title> | |
<style>img { | |
max-width: 200px; | |
}</style> | |
</head> | |
<body> | |
<button id="btn">Начать загрузку</button> | |
<script src="index.js"></script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const btn = document.getElementById('btn') | |
const arr = [ | |
'1.jpeg', | |
'FAILED2.jpg', | |
'3.jpeg', | |
'4.jpg' | |
] | |
function creatImg(imgPath, img1) { | |
return new Promise((resolve, reject) => { | |
try { | |
let img = document.createElement('img') | |
img.setAttribute('src', imgPath) | |
img.setAttribute('id', img1) | |
const body = document.querySelector('body') | |
body.appendChild(img) | |
document.getElementById(img1).addEventListener('load', () => { | |
resolve(`фото загрузилось - ${imgPath}`) | |
}) | |
document.getElementById(img1).addEventListener('error', () => { | |
reject(`Ошибка при загрузки изображения - ${imgPath}`) | |
}) | |
} catch (e) { | |
reject(`Ошибка при загрузки изображения - ${imgPath}`) | |
} | |
}) | |
} | |
btn.addEventListener('click', () => { | |
creatImg(arr[0], 'id01') | |
.then(response => { | |
console.log(response) | |
return creatImg(arr[1], 'id02') | |
}, | |
() => creatImg(arr[1], 'id02')) | |
.then(response => { | |
console.log(response) | |
return creatImg(arr[2], 'id03') | |
}, | |
() => creatImg(arr[2], 'id03')) | |
.then(response => { | |
console.log(response) | |
return creatImg(arr[3], 'id04') | |
}, | |
() => creatImg(arr[3], 'id04')) | |
.catch(err => console.log('error!!!', err)) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment