Skip to content

Instantly share code, notes, and snippets.

@belocer

belocer/index.html

Created Feb 11, 2021
Embed
What would you like to do?
Обработка ошибок в Promise
<!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>
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