Init asynchonous programming example

This commit is contained in:
2023-08-10 17:30:55 +07:00
parent dcc8ce8f3b
commit 4b73bcdb07
2 changed files with 69 additions and 0 deletions
+12
View File
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Javascript Training</title>
</head>
<body>
<h1>Javascript Training</h1>
<script src="./index.js"></script>
</body>
</html>
+57
View File
@@ -0,0 +1,57 @@
// Callbacks
const task1 = (callAgain) => {
setTimeout(() => {
callAgain("Task 1");
}, 2000);
};
// Promise
var promise = new Promise(
// Executor
function (resolve, reject) {
// Logic
// Successfull: resolve()
// Failure: reject()
task1((result) => {
resolve(result);
});
}
);
promise
.then(function (number) {
console.log("Then 1");
return number;
})
.then(function (data) {
return new Promise(function (resolve) {
console.log(`Then 2: ${data}`);
setTimeout(function () {
resolve(1000);
}, 5000);
});
})
.then(function (data) {
console.log(`Then 3: ${data}`);
})
.catch(function () {
console.log("Failure!");
})
.finally(function () {
console.log("Done!");
});
// Async, await
const getNewToDo = async () => {
let response = await fetch("https://jsonplaceholder.typicode.com/posts");
let data = await response.json();
return data;
};
getNewToDo().then((data) => {
console.log(">>> Data: ", data);
});