Skip to content

Commit

Permalink
adding async await examples to learning area
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisdavidmills committed Feb 21, 2019
1 parent e610713 commit 12d9c47
Show file tree
Hide file tree
Showing 20 changed files with 398 additions and 50 deletions.
Binary file added javascript/asynchronous/async-await/coffee.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions javascript/asynchronous/async-await/description.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
I just love coffee and tea, they really help me to think, I am filled with more ideas, the more of them I drink.
37 changes: 37 additions & 0 deletions javascript/asynchronous/async-await/fast-async-await.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Demonstration of fast async/await</title>
</head>
<body>
<script>
// Define custom promise function

function timeoutPromise(interval) {
return new Promise((resolve, reject) => {
setTimeout(function(){
resolve("done");
}, interval);
});
};

async function timeTest() {
const timeoutPromise1 = timeoutPromise(3000);
const timeoutPromise2 = timeoutPromise(3000);
const timeoutPromise3 = timeoutPromise(3000);

await timeoutPromise1;
await timeoutPromise2;
await timeoutPromise3;
}

let startTime = Date.now();
timeTest().then(() => {
let finishTime = Date.now();
let timeTaken = finishTime - startTime;
alert("Time taken in milliseconds: " + timeTaken);
})
</script>
</body>
</html>
62 changes: 62 additions & 0 deletions javascript/asynchronous/async-await/promise-all-async-await.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>promise.all() example with async/await</title>
</head>
<body>
<script>
// Define function to fetch a file and return it in a usable form
async function fetchAndDecode(url, type) {
try {
// Returning the top level promise, so the result of the entire chain is returned out of the function
let response = await fetch(url);

let content;

// Depending on what type of file is being fetched, use the relevant function to decode its contents
if(type === 'blob') {
content = await response.blob();
} else if(type === 'text') {
content = await response.text();
}

return content;
} catch(e) {
console.log(`There has been a problem with your fetch operation for resource "${url}": ` + e.message);
}
}

async function displayContent() {
// Call the fetchAndDecode() method to fetch the images and the text, and store their promises in variables
let coffee = fetchAndDecode('coffee.jpg', 'blob');
let tea = fetchAndDecode('tea.jpg', 'blob');
let description = fetchAndDecode('description.txt', 'text');

// Use Promise.all() to run code only when all three function calls have resolved
let values = await Promise.all([coffee, tea, description]);

console.log(values);
// Store each value returned from the promises in separate variables; create object URLs from the blobs
let objectURL1 = URL.createObjectURL(values[0]);
let objectURL2 = URL.createObjectURL(values[1]);
let descText = values[2];

// Display the images in <img> elements
let image1 = document.createElement('img');
let image2 = document.createElement('img');
image1.src = objectURL1;
image2.src = objectURL2;
document.body.appendChild(image1);
document.body.appendChild(image2);

// Display the text in a paragraph
let para = document.createElement('p');
para.textContent = descText;
document.body.appendChild(para);
}

displayContent();
</script>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>fetch() promise.finally() example with async/await</title>
</head>
<body>
<script>
// Define function to fetch a file and return it in a usable form
async function fetchAndDecode(url, type) {
try {
// Returning the top level promise, so the result of the entire chain is returned out of the function
let response = await fetch(url);

let content;

// Depending on what type of file is being fetched, use the relevant function to decode its contents
if(type === 'blob') {
content = await response.blob();
} else if(type === 'text') {
content = await response.text();
}

return content;
} catch(e) {
console.log(`There has been a problem with your fetch operation for resource "${url}": ` + e.message);
} finally {
console.log(`fetch attempt for "${url}" finished.`);
};
}

async function displayContent() {
// Call the fetchAndDecode() method to fetch the images and the text, and store their promises in variables
let coffee = fetchAndDecode('coffee.jpg', 'blob');
let tea = fetchAndDecode('tea.jpg', 'blob');
let description = fetchAndDecode('description.txt', 'text');

// Use Promise.all() to run code only when all three function calls have resolved
let values = await Promise.all([coffee, tea, description]);

console.log(values);
// Store each value returned from the promises in separate variables; create object URLs from the blobs
let objectURL1 = URL.createObjectURL(values[0]);
let objectURL2 = URL.createObjectURL(values[1]);
let descText = values[2];

// Display the images in <img> elements
let image1 = document.createElement('img');
let image2 = document.createElement('img');
image1.src = objectURL1;
image2.src = objectURL2;
document.body.appendChild(image1);
document.body.appendChild(image2);

// Display the text in a paragraph
let para = document.createElement('p');
para.textContent = descText;
document.body.appendChild(para);
}

displayContent();
</script>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Simple fetch() with async/await</title>
</head>
<body>
<script>
// Call the fetch() method to fetch the image, and store it in a variable
async function myFetch() {
// try {
let response = await fetch('coffee.jpg');
// Use a then() block to respond to the promise's successful completion
// by taking the returned response and running blob() on it to transform it into a blob
let myBlob = await response.blob();
// blob() also returns a promise; when it successfully completes it returns
// The blob object in the callback

// Create an object URL that points to the blob object
let objectURL = URL.createObjectURL(myBlob);
// Create an <img> element to display the blob (it's an image)
let image = document.createElement('img');
// Set the src of the <img> to the object URL so the image displays it
image.src = objectURL;
// Append the <img> element to the DOM
document.body.appendChild(image);
// } catch(e) {
// console.log(e);
// }
}

myFetch().catch((e) => console.log(e));
</script>
</body>
</html>
31 changes: 31 additions & 0 deletions javascript/asynchronous/async-await/simple-fetch-async-await.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Simple fetch() with async/await</title>
</head>
<body>
<script>
// Call the fetch() method to fetch the image, and store it in a variable
async function myFetch() {
let response = await fetch('coffee.jpg');
// Use a then() block to respond to the promise's successful completion
// by taking the returned response and running blob() on it to transform it into a blob
return await response.blob();
// blob() also returns a promise; when it successfully completes it returns
// The blob object in the callback
}

myFetch().then((blob) => {
// Create an object URL that points to the blob object
let objectURL = URL.createObjectURL(blob);
// Create an <img> element to display the blob (it's an image)
let image = document.createElement('img');
// Set the src of the <img> to the object URL so the image displays it
image.src = objectURL;
// Append the <img> element to the DOM
document.body.appendChild(image);
});
</script>
</body>
</html>
33 changes: 33 additions & 0 deletions javascript/asynchronous/async-await/slow-async-await.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Demonstration of slow async/await</title>
</head>
<body>
<script>
// Define custom promise function

function timeoutPromise(interval) {
return new Promise((resolve, reject) => {
setTimeout(function(){
resolve("done");
}, interval);
});
};

async function timeTest() {
await timeoutPromise(3000);
await timeoutPromise(3000);
await timeoutPromise(3000);
}

let startTime = Date.now();
timeTest().then(() => {
let finishTime = Date.now();
let timeTaken = finishTime - startTime;
alert("Time taken in milliseconds: " + timeTaken);
})
</script>
</body>
</html>
Binary file added javascript/asynchronous/async-await/tea.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
</head>
<body>
<script>
function greeting(name) {
function greet(name) {
alert('Hello ' + name);
}

Expand All @@ -15,7 +15,7 @@
callback(name);
}

processUserInput(greeting);
processUserInput(greet);
</script>
</body>
</html>
14 changes: 7 additions & 7 deletions javascript/asynchronous/introducing/simple-sync.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@
<body>
<button>Click me</button>
<script>
let pElem = document.createElement('p');
pElem.textContent = 'This is some example text';
document.body.appendChild(pElem);

const btn = document.querySelector('button');
btn.addEventListener('click', () =>
alert('You clicked me!')
);
btn.addEventListener('click', () => {
alert('You clicked me!');

let pElem = document.createElement('p');
pElem.textContent = 'This is a newly-added paragraph.';
document.body.appendChild(pElem);
});
</script>
</body>
</html>
32 changes: 32 additions & 0 deletions javascript/asynchronous/introducing/xhr-async-callback.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Simple XHR async callback example</title>
</head>
<body>
<script>
function loadAsset(url, type, callback) {
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = type;

xhr.onload = function() {
callback(xhr.response);
};

xhr.send();
}

function displayImage(blob) {
let objectURL = URL.createObjectURL(blob);

let image = document.createElement('img');
image.src = objectURL;
document.body.appendChild(image);
}

loadAsset('coffee.jpg', 'blob', displayImage);
</script>
</body>
</html>
Loading

0 comments on commit 12d9c47

Please sign in to comment.