Skip to content

Commit fbe57b5

Browse files
committed
Asynchronous-JavaScript 🗽🔗
1 parent 3bb5a7b commit fbe57b5

File tree

8 files changed

+329
-0
lines changed

8 files changed

+329
-0
lines changed
+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
4+
<head>
5+
<meta charset="UTF-8">
6+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
7+
<meta http-equiv="X-UA-Compatible" content="ie=edge">
8+
<title>AJAX</title>
9+
</head>
10+
11+
<body>
12+
13+
<h1>AJAX FETCH</h1>
14+
15+
16+
<script>
17+
18+
function getWeather(woeid) {
19+
fetch(`https://crossorigin.me/https://www.metaweather.com/api/location/${woeid}/`)
20+
21+
.then(result => {
22+
// console.log(result);
23+
return result.json();
24+
})
25+
26+
.then(data => {
27+
// console.log(data);
28+
const today = data.consolidated_weather[0];
29+
console.log(`Temperatures today in ${data.title} stay between ${today.min_temp} and ${today.max_temp}.`);
30+
})
31+
32+
.catch(error => console.log(error));
33+
}
34+
35+
36+
getWeather(2487956);
37+
getWeather(44418);
38+
39+
// async/await way
40+
async function getWeatherAW(woeid) {
41+
try {
42+
const result = await fetch(`https://crossorigin.me/https://www.metaweather.com/api/location/${woeid}/`);
43+
44+
const data = await result.json();
45+
const tomorrow = data.consolidated_weather[1];
46+
47+
console.log(`Temperatures tomorrow in ${data.title} stay between ${tomorrow.min_temp} and ${tomorrow.max_temp}.`);
48+
49+
return data;
50+
51+
} catch (error) {
52+
alert(error);
53+
}
54+
}
55+
56+
getWeatherAW(2487956);
57+
58+
let dataLondon;
59+
getWeatherAW(44418).then(data => {
60+
dataLondon = data
61+
console.log(dataLondon);
62+
});
63+
64+
</script>
65+
66+
</body>
67+
68+
</html>

Asynchronous-JavaScript/AsyncAwait.js

+75
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
// In ES6 to consume promises syntax can still be quite confusing and difficult to manage.And, so in ES8, or ES2017, something alled Async/Await was introduced to the JavaScript language.
2+
3+
const getIDs = new Promise((resolve, reject) => {
4+
setTimeout(() => {
5+
resolve([523, 883, 432, 974]);
6+
}, 1500);
7+
});
8+
9+
const getRecipe = recID => {
10+
return new Promise((resolve, reject) => {
11+
setTimeout(ID => {
12+
13+
const recipe = {
14+
title: 'Fresh tomato Pasta',
15+
Publisher: 'Lakshman'
16+
};
17+
18+
resolve(`${ID}: ${recipe.title}`);
19+
20+
}, 1500, recID);
21+
});
22+
};
23+
24+
const getRelated = Publisher => {
25+
return new Promise((resolve, reject) => {
26+
setTimeout(pub => {
27+
const recipe = {
28+
title: 'American Pizza',
29+
Publisher: pub
30+
};
31+
32+
resolve(`${pub}: ${recipe.title}`);
33+
34+
}, 1500, Publisher);
35+
});
36+
};
37+
38+
/*
39+
// this then method allows us to add an event handler for the case that the promise is fulfilled. So which means that there is a result.
40+
getIDs
41+
.then(IDs => { // so this argument here will be the result of the successful promise.
42+
console.log(IDs); // [ 523, 883, 432, 974 ]
43+
return getRecipe(IDs[2]);
44+
})
45+
46+
.then(recipe => {
47+
console.log(recipe); // 432: Fresh tomato Pasta
48+
return getRelated('Lakshman Gope');
49+
})
50+
51+
.then(recipe => {
52+
console.log(recipe); // Lakshman Gope: American Pizza
53+
54+
})
55+
// if the promise rejected then catch method will catch the error.
56+
.catch(error => {
57+
console.log('Error: ' + error);
58+
}); */
59+
60+
61+
// it's good to remember that async function always returns a promise.
62+
async function getRecipeAW() {
63+
const IDs = await getIDs;
64+
console.log(IDs); // [ 523, 883, 432, 974 ]
65+
66+
const recipe = await getRecipe(IDs[2]);
67+
console.log(recipe); // 432: Fresh tomato Pasta
68+
69+
const related = await getRelated('Lakshman Gope');
70+
console.log(related); // Lakshman Gope: American Pizza
71+
72+
return recipe;
73+
}
74+
75+
getRecipeAW().then(result => console.log(`${result} is the best ever!`)); // 432: Fresh tomato Pasta is the best ever!
+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
const second = () => {
2+
setTimeout(() => {
3+
console.log('Async Hey there');
4+
5+
}, 2000);
6+
}
7+
8+
const first = () => {
9+
console.log('Hey there');
10+
second();
11+
console.log('The end');
12+
}
13+
14+
first();

Asynchronous-JavaScript/Callbacks.js

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// The Old Way: Asynchronous JavaScript with Callbacks
2+
3+
function getRecipe() {
4+
setTimeout(() => {
5+
const recipeID = [523, 883, 432, 974];
6+
console.log(recipeID); // 1
7+
8+
setTimeout(id => {
9+
const recipe = {
10+
title: 'Fresh tomato Pasta',
11+
Publisher: 'Lakshman'
12+
};
13+
console.log(`${id}: ${recipe.title}`); // 2
14+
15+
setTimeout(Publisher => {
16+
const recipe2 = {
17+
title: 'American Pizza',
18+
Publisher: Publisher
19+
};
20+
21+
console.log(recipe2); // 3
22+
23+
}, 1500, recipe.Publisher);
24+
25+
}, 1500, recipeID[2]);
26+
27+
28+
29+
}, 1500);
30+
}
31+
32+
getRecipe();

Asynchronous-JavaScript/Callbacks1.js

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
setTimeout(() => {
2+
console.log('Two seconds are up!');
3+
4+
}, 2000);
5+
6+
const names = ['Lakshman', 'Gope', 'Proddut'];
7+
const shortNames = names.filter((name) => {
8+
return name.length <= 4;
9+
});
10+
11+
const geocode = (address, callback) => {
12+
setTimeout(() => {
13+
const data = {
14+
latitude: 0,
15+
longitude: 0
16+
}
17+
18+
callback(data);
19+
20+
}, 2000);
21+
};
22+
23+
geocode('Dhaka', (data) => {
24+
console.log(data);
25+
});
26+
27+
28+
// Challenge
29+
// Goal: Mess around with the callback pattern
30+
//
31+
// 1. Define an add function that accepts the correct arguments
32+
// 2. Use setTimeout to simulate a 2 second delay
33+
// 3. After 2 seconds are up, call the callback function with the sum
34+
// 4. Test your work!
35+
36+
37+
const add = (a, b, callback) => {
38+
setTimeout(() => {
39+
callback(a + b);
40+
}, 2000);
41+
}
42+
43+
add(1, 4, (sum) => {
44+
console.log(sum) // Should print: 5
45+
})

Asynchronous-JavaScript/Promises.js

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
// From Callback Hell to Promises (ES6)
2+
3+
/* Promises, which is an ES six feature designed specifically
4+
to deal with asynchronous JavaScript. In simple terms a promise is an object
5+
that keeps track about whether a certain event
6+
has happened already or not, and if it did happen,
7+
then the promise determines what happens next. A promise kind of implements the concept
8+
of a future value that we're expecting.*/
9+
10+
const getIDs = new Promise((resolve, reject) => {
11+
setTimeout(() => {
12+
resolve([523, 883, 432, 974]);
13+
}, 1500);
14+
});
15+
16+
const getRecipe = recID => {
17+
return new Promise((resolve, reject) => {
18+
setTimeout(ID => {
19+
20+
const recipe = {
21+
title: 'Fresh tomato Pasta',
22+
Publisher: 'Lakshman'
23+
};
24+
25+
resolve(`${ID}: ${recipe.title}`);
26+
27+
}, 1500, recID);
28+
});
29+
};
30+
31+
const getRelated = Publisher => {
32+
return new Promise((resolve, reject) => {
33+
setTimeout(pub => {
34+
const recipe = {
35+
title: 'American Pizza',
36+
Publisher: pub
37+
};
38+
39+
resolve(`${pub}: ${recipe.title}`); // 3
40+
41+
}, 1500, Publisher);
42+
});
43+
};
44+
45+
46+
// this then method allows us to add an event handler for the case that the promise is fulfilled. So which means that there is a result.
47+
getIDs
48+
.then(IDs => { // so this argument here will be the result of the successful promise.
49+
console.log(IDs); // [ 523, 883, 432, 974 ]
50+
return getRecipe(IDs[2]);
51+
})
52+
53+
.then(recipe => {
54+
console.log(recipe); // 432: Fresh tomato Pasta
55+
return getRelated('Lakshman Gope');
56+
})
57+
58+
.then(recipe => {
59+
console.log(recipe); // Lakshman Gope: American Pizza
60+
61+
})
62+
// if the promise rejected then catch method will catch the error.
63+
.catch(error => {
64+
console.log('Error: ' + error);
65+
});
+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
const numbers = [1, 3, 6];
2+
const addTwo = async (num) => num + 2;
3+
const numbersPlusTwo = numbers.map(addTwo);
4+
console.log(numbersPlusTwo);
+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
const https = require('https')
2+
const url = 'https://api.darksky.net/forecast/9d1465c6f3bb7a6c71944bdd8548d026/44.1545,-75.7088';
3+
4+
const request = https.request(url, (response) => {
5+
let data = ''
6+
7+
response.on('data', (chunk) => {
8+
data = data + chunk.toString()
9+
console.log('json converted to string!');
10+
11+
})
12+
13+
response.on('end', () => {
14+
console.log('At the end!');
15+
16+
const body = JSON.parse(data)
17+
console.log(body)
18+
})
19+
20+
})
21+
22+
request.on('error', (error) => {
23+
console.log('An error', error)
24+
})
25+
26+
request.end()

0 commit comments

Comments
 (0)