mirror of
https://github.com/Nezumi-2711/javascript-training.git
synced 2026-09-22 13:38:43 +00:00
Init asynchonous programming example
This commit is contained in:
@@ -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>
|
||||
@@ -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);
|
||||
});
|
||||
Reference in New Issue
Block a user