-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpromise-reject-example.js
More file actions
31 lines (27 loc) · 869 Bytes
/
promise-reject-example.js
File metadata and controls
31 lines (27 loc) · 869 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// callbacks, promises, async/await
const heading1 = document.querySelector(".heading-1");
const heading2 = document.querySelector(".heading-2");
const heading3 = document.querySelector(".heading-3");
const imgContainer = document.querySelector(".img-container");
const btn = document.querySelector(".btn");
const url = "https://picsum.photos/1000 ";
btn.addEventListener("click", () => {
loadImage(url)
.then((data) => imgContainer.appendChild(data))
.catch((error) => {
console.log(error);
});
});
function loadImage(url) {
const promise = new Promise((resolve, reject) => {
const img = new Image();
img.addEventListener("load", () => {
resolve(img);
});
img.addEventListener("error", () => {
reject(new Error(`Failed to load image from the source: ${url}`));
});
img.src = url;
});
return promise;
}