setTimeoutを用いた非同期処理
console.log(1); setTimeout(()=> console.log(2), 5000); console.log(3);
1->3->2の順番で処理される
		const sleep = (second) => {
			const startTime = new Date();
			while (new Date() - startTime < second);
			console.log("done sleep");
		}
		const button = document.querySelector("button");
		button.addEventListener("click", () => console.log("clicked"));
		sleep(5000)
処理される順番 : setTimeout実行中に次のタスクが実行される
		const first = () => {
			setTimeout(() => console.log("task1 done"), 2000);
			console.log("function frist done");
		}
		const second = () => console.log("function second done");
		first();
		second();
### Promiseとは?
Promiseとは非同期処理をより簡単かつ可動性が上がるように書けるようにしたJavaScriptのオブジェクト
Promiseは3つの状態がある
– pending: 非同期処理の実行中の状態を表す
– fulfilled: 非同期処理が正常終了した状態を表す
– rejected: 非同期処理が異常終了した状態を表す
new Promise( ).then( ).catch( ).finally( );
引数としてコールバック関数をとる
new Promise((resolve, reject) => {
}).then(
).catch(
).finally(
);
### resolve
Promiseの状態がfulfilled(正常終了)になったらresolveが実行される
resolveが実行された場合は、thenメソッドが実行される
thenメソッドが実行された場合catchメソッドはm無視され、最後にfinallyメソッドが実行される
new Promise((resolve, reject) => {
	resolve("hoge");
}).then((data)=>console.log(data)
).catch(
).finally(()=>console.log("finally")
);
### reject
Promiseの状態がrejectedになったらrejectが実行される
rejectはPromise内のコールバック実行中に何らかのエラーが発生しそれをPromiseに通知するために使用する関数
rejectが実行される場合はcatchメソッドのコールバック関数が実行される
new Promise((resolve, reject) => reject("fuga")
.then(
).catch((data)=> console.log(data))
.finally(()=>console.log("finally")
);
Promiseオブジェクト内の同期・非同期処理の関係
new Promise((resolve, reject) => {
 // 同期処理
}).then(
 // resolveの実行を待って非同期処理
).catch(
 // rejectの実行を待って非同期処理
).finally(
 // resolveかrejectの実行を待って非同期処理
);
	new Promise((resolve, reject) => {
	 console.log("Promise");
	  resolve();
	}).then(() => console.log("then"));
	console.log("global end");
Promiseオブジェクトを使った並列処理
– Promise.all => 並列処理している全てが完了したら後続処理に続く
	const sleep = (val) => {
		return new Promise((resolve) => {
			setTimeout(() => {
				console.log(val++);
				resolve(val);
			}, 1000);
		});
	};
	Promise.all([sleep(0), sleep(1), sleep(2)]).then(() => console.log("end"));
AsyncとAwait
AsyncとAwaitはPromiseを更に直感的に書けるようにしたもの
– Async
Asyncを使って宣言された関数はPromiseオブジェクトを返却する
関数宣言の先頭にAsyncがついていたらPromiseオブジェクトがreturnされる。thenメソッドにつなげられる。
– Await
AwaitはPromiseを返却する関数の非同期処理が終わるのを待つ記述
Awaitで受けられるものはPromiseのインスタンス
	const sleep = (val) => {
		return new Promise((resolve) => {
			setTimeout(() => {
				resolve(val);
			}, 1000);
		});
	};
	async function init() {
		console.log(await sleep(0));
	}
	init();
fetchという関数
fetchを使うことでサーバからデータを取得できる
	fetch("")
		.then((response) => {
			return response.json();
		})
		.then((json) => {
			console.log(json);
		});
	 
					 
