A2Z week3 -1
Fri Sep 29 2023 06:20:50 GMT+0000 (Coordinated Universal Time)
Saved by
@yc_lan
<body style="width:50%">
<h1>Fetch a Rainbow</h1>
<img src="" id="rainbow" width="100%" />
<br/><br/><br/>
<hr>
<h1>Fetch a Rainbow by Async</h1>
<img src="" id="rainbowbyasync" width="100%" />
<script>
// call the fetch(path) function
// ⬇️ Promise
// response ()
// ⬇️ text, bolb,json...
// complete data string
// make an <img> with these data
console.log('about to fetch a rainbow');
//fetch .then
fetch('rainbow.jpg')
.then(response => {
console.log(response);
return response.blob();
})
.then(blob => {
console.log(blob);
document.getElementById('rainbow').src=URL.createObjectURL(blob);
})
.catch(error => {
console.log("error");
console.log(error);
})
//================================================================
//async
async function catchRainbow() {
let response = await fetch('rainbow.jpg');
let blob = await response.blob();
document.getElementById('rainbowbyasync').src = URL.createObjectURL(blob);
}
//call the function catchRainbow
catchRainbow()
.then(response => {
console.log('yay');
})
.catch(error => {
console.log('error!');
console.error(error);
});
</script>
content_copyCOPY
Comments