- HTMLとJavaScriptの下準備をする
- setTimeoutを使う
- Promiseを使う
- fetchを使う(APIを使って外部サービスとデータのやりとりを行う)
-
-
Save tsuyopon-xyz/ed806925fa423a625ad3b0da61e8dfdd to your computer and use it in GitHub Desktop.
【コールバック基礎講座】(コールバック関数の利用例)コールバック関数を使って非同期処理を実装する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="ja"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>非同期処理のテスト</title> | |
</head> | |
<body> | |
<h1>非同期テスト</h1> | |
<script src="main.js"></script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 2. setTimeoutを使う | |
console.log('111'); | |
setTimeout(() => { | |
console.log('setTimeoutの中'); | |
}, 1000); | |
console.log('222'); | |
// 3. Promiseを使う | |
const promise = new Promise((resolve, reject) => { | |
setTimeout(() => { | |
console.log('promiseの中のsetTimeout'); | |
resolve('何かしらのデータ'); | |
}, 2000); | |
}); | |
promise.then((data) => { | |
console.log('thenの中'); | |
console.log('data : ', data); | |
}) | |
// 4. fetchを使う(APIを使って外部サービスとデータのやりとりを行う) | |
fetch('https://opentdb.com/api.php?amount=10') | |
.then((response) => { | |
console.log('response : ', response); | |
return response.json(); | |
}) | |
.then((data) => { | |
console.log('data : ', data); | |
}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment