Skip to content

Instantly share code, notes, and snippets.

@tsuyopon-xyz
Created September 30, 2020 07:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsuyopon-xyz/ed806925fa423a625ad3b0da61e8dfdd to your computer and use it in GitHub Desktop.
Save tsuyopon-xyz/ed806925fa423a625ad3b0da61e8dfdd to your computer and use it in GitHub Desktop.
【コールバック基礎講座】(コールバック関数の利用例)コールバック関数を使って非同期処理を実装する
<!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>
// 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