ASYNC JavaScript (CALLBACK, PROMISES, ASYNC AWAIT) video (ok)
https://www.youtube.com/watch?v=XYVJKnZc0SY
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Async</title>
</head>
<body>
<img id="pic1"></img>
<img id="pic2"></img>
<img id="pic3"></img>
<script type="text/javascript">
function httpGetAsync(theUrl, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() { //Call a function when the state changes.
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) callback(xmlHttp);
}
xmlHttp.open('GET', theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
// ---------------------- Part 1 ----------------------
// httpGetAsync('https://loremflickr.com/320/240',(data)=>{
// document.getElementById('pic1').setAttribute('src',data.responseURL);
// httpGetAsync('https://loremflickr.com/320/240',(data)=>{
// document.getElementById('pic2').setAttribute('src',data.responseURL);
// httpGetAsync('https://loremflickr.com/320/240',(data)=>{
// document.getElementById('pic3').setAttribute('src',data.responseURL);
// });
// });
// });
// ---------------------- Part 2 ----------------------
const currentPromise1 = new Promise((resolve, reject) => {
httpGetAsync('https://loremflickr.com/320/240', resolve);
});
const currentPromise2 = new Promise((resolve, reject) => {
httpGetAsync('https://loremflickr.com/320/240', resolve);
});
const currentPromise3 = new Promise((resolve, reject) => {
httpGetAsync('https://loremflickr.com/320/240', resolve);
});
// currentPromise1
// .then((data) => {
// document.getElementById('pic1').setAttribute('src', data.responseURL);
// }).catch((error) => {
// console.log(error);
// });
// currentPromise2
// .then((data) => {
// document.getElementById('pic2').setAttribute('src', data.responseURL);
// }).catch((error) => {
// console.log(error);
// });
// currentPromise3
// .then((data) => {
// document.getElementById('pic3').setAttribute('src', data.responseURL);
// }).catch((error) => {
// console.log(error);
// });
// ---------------------- Part 3 ----------------------
const execute = async () => {
try {
const response1 = await currentPromise1;
document.getElementById('pic1').setAttribute('src', response1.responseURL);
const response2 = await currentPromise2;
document.getElementById('pic2').setAttribute('src', response2.responseURL);
const response3 = await currentPromise3;
document.getElementById('pic3').setAttribute('src', response3.responseURL);
} catch (error) {
console.log("{0} exception caught.", error);
}
}
execute();
</script>
</body>
</html>
PreviousPopup slide up from the bottom overflowing other div blocks (ok)Next=== START jQuery Mobile ===
Last updated