戻る

asyncとawaitによる同期処理
javascriptで順番を守って実行したい場合は
asyncとawaitを使って実装する方法があります。

サンプル
 

copy
const b1 = document.getElementById("btn1");
const b2 = document.getElementById("btn2");
let pageIndex=0;
let pageMax=8;
displayScreen();
//戻る
b1.addEventListener("click", () => 
{
	//画像を表示する
	//ストーリーを表示する
	//ボタンの表示有無
	pageIndex--;
	if(pageIndex < 0) pageIndex = 0;
	displayScreen(pageIndex, 0);
});
//進む
b2.addEventListener("click", () => 
{
	pageIndex++;
	if(pageIndex >= pageMax)pageIndex = pageMax - 1;
	displayScreen(pageIndex, 1);
});
async function displayScreen()
{
	await task1();//画像
	await task2();//ストーリー
	await task3();//ページ番号
	await task4();//ボタン表示切り替え
}
//画像
async function task1()
{
	return new Promise(resolve =>
	{
		let path = "";// ex.)img/
		let file = "";
		switch(pageIndex)
		{
			case 0:
				file ="nawmin_sample2.png";//くま
				break;
			case 1:
				file ="nawmin_sample4.png";//農家の人
				break;
			case 2:
				file ="nawmin_sample2.png";//くま
				break;
			case 3:
				file ="nawmin_sample5.png";//野菜セット
				break;
			case 4:
				file ="nawmin_sample2.png";//くま
				break;
			case 5:
				file ="nawmin_sample3.png";//どんぐり
				break;
			case 6:
				file ="nawmin_sample2.png";//くま
				break;
			case 7:
				file ="nawmin_sample4.png";//農家の人
				break;
		}
		const d1 = document.getElementById("screen");
		d1.src=path+file;
		resolve();
	});
}
//ストーリー
async function task2()
{
	return new Promise(resolve =>
	{
		let story = "";
		switch(pageIndex)
		{
			case 0:
				story = "こんにちは";
				break;
			case 1:
				story = "おや、どうしたんだい?";
				break;
			case 2:
				story = "お腹へっちゃって";
				break;
			case 3:
				story = "野菜はどう?";
				break;
			case 4:
				story = "それは、ちょっと";
				break;
			case 5:
				story = "あぁ、そういえばこれ拾ったんだった。\n(どんぐりを差し出す)";
				break;
			case 6:
				story = "いいの?\nありがとう";
				break;
			case 7:
				story = "どういたしまして\n(こうしてくまさん森へ帰っていきました。)";
				break;
		}
		const d1 = document.getElementById("story");
		d1.innerText = story;
		resolve();
	});
}
//ページ番号
async function task3()
{
	return new Promise(resolve =>
	{
		const d1 = document.getElementById("pageNo");
		d1.textContent = (pageIndex + 1) + "/" + pageMax;
		resolve();
	});
}
//ボタン表示切り替え
async function task4()
{
	return new Promise(resolve =>
	{
		const b1 = document.getElementById("btn1");
		const b2 = document.getElementById("btn2");
		b1.style.visibility="visible";
		b2.style.visibility="visible";
		if(pageIndex==0)
		{
			b1.style.visibility="hidden";
			
		}
		if(pageIndex + 1 == pageMax)
		{
			b2.style.visibility="hidden";
		}
		resolve();
	});
}
b1.addEventListener("click", () =>
前のページに戻ります。
pageIndex(ページ番号のインデックス)をデクリメントします。
pageIndex--;
if(pageIndex < 0) pageIndex = 0;
一番先頭でデクリメントするとマイナスになってしまうため0にします。

b2.addEventListener("click", () =>
次のページに進みます。
pageIndex(ページ番号のインデックス)をデクリメントします。
pageIndex++;
if(pageIndex >= pageMax)pageIndex = pageMax - 1;
一番最後でインクリメントすると最後の要素インデックスを超えてしまうため「最後のページ - 1」にします。

async function displayScreen()
asyncをつけることで、その関数ではPromiseオブジェクトを返すようになります。
await task1();//画像
await task2();//ストーリー
await task3();//ページ番号
await task4();//ボタン表示切り替え
awaitはPromiseオブジェクトの状態が確定するまでの処理を一時中断する動作をします。

return new Promise(resolve =>
Promise関数は2つの引数を持っています。
1個目が実行するメソッドです。
2個目はエラーの場合に処理するメソッドを設定することができるのですが、任意となり、このサンプルでは使用していません。
1個目のメソッドを実行することでPromise関数に処理の終了を伝えることができます。

resolve();
引数と同じメソッド名を実行することで、このPromise関数の処理が終わることを意味します。
そして、この第1引数にメソッドを設定した場合、そのメソッドの処理が終わり次第、Promise関数の処理が終わることになります。
途中でエラーになった場合は、第2引数のエラー判定処理を実行することで仕様上の対応処理が可能となります。

[謝辞]
「イラスト:農民イラスト」さんの画像を使用させていただいております。
ありがとうございます。
[URL]イラスト:農民イラスト
URL[https://nawmin.stores.jp][クリックすると開きます])


戻る
back

Synchronous processing with async and await
if you wanto to execute things in order unsing JavaScript,
you can implement it using async and await.

Sample
 

copy
const b1 = document.getElementById("btn1");
const b2 = document.getElementById("btn2");
let pageIndex=0;
let pageMax=8;
displayScreen();
//back
b1.addEventListener("click", () => 
{
	//Displaying images
	//View the story
	//Display of button
	pageIndex--;
	if(pageIndex < 0) pageIndex = 0;
	displayScreen(pageIndex, 0);
});
//forward
b2.addEventListener("click", () => 
{
	pageIndex++;
	if(pageIndex >= pageMax)pageIndex = pageMax - 1;
	displayScreen(pageIndex, 1);
});
async function displayScreen()
{
	await task1();//image
	await task2();//story
	await task3();//page no
	await task4();//Button display switching
}
//image
async function task1()
{
	return new Promise(resolve =>
	{
		let path = "";// ex.)img/
		let file = "";
		switch(pageIndex)
		{
			case 0:
				file ="nawmin_sample2.png";//bear
				break;
			case 1:
				file ="nawmin_sample4.png";//Farmer
				break;
			case 2:
				file ="nawmin_sample2.png";//bear
				break;
			case 3:
				file ="nawmin_sample5.png";//Vegetable set
				break;
			case 4:
				file ="nawmin_sample2.png";//bear
				break;
			case 5:
				file ="nawmin_sample3.png";//Acorns
				break;
			case 6:
				file ="nawmin_sample2.png";//bear
				break;
			case 7:
				file ="nawmin_sample4.png";//Farmer
				break;
		}
		const d1 = document.getElementById("screen");
		d1.src=path+file;
		resolve();
	});
}
//story
async function task2()
{
	return new Promise(resolve =>
	{
		let story = "";
		switch(pageIndex)
		{
			case 0:
				story = "Hello";
				break;
			case 1:
				story = "Hey, what's wrong?";
				break;
			case 2:
				story = "I'm hungry";
				break;
			case 3:
				story = "What about vegetables?";
				break;
			case 4:
				story = "That's a bit";
				break;
			case 5:
				story = "Ah, that reminds me, I picked this up. \n (Hands over the acorn)";
				break;
			case 6:
				story = "Is that okay?\nThank you";
				break;
			case 7:
				story = "You're welcome.\n(And so the bear returned to the forest.)";
				break;
		}
		const d1 = document.getElementById("story");
		d1.innerText = story;
		resolve();
	});
}
//page no
async function task3()
{
	return new Promise(resolve =>
	{
		const d1 = document.getElementById("pageNo");
		d1.textContent = (pageIndex + 1) + "/" + pageMax;
		resolve();
	});
}
//Button display switching
async function task4()
{
	return new Promise(resolve =>
	{
		const b1 = document.getElementById("btn1");
		const b2 = document.getElementById("btn2");
		b1.style.visibility="visible";
		b2.style.visibility="visible";
		if(pageIndex==0)
		{
			b1.style.visibility="hidden";
			
		}
		if(pageIndex + 1 == pageMax)
		{
			b2.style.visibility="hidden";
		}
		resolve();
	});
}
b1.addEventListener("click", () =>
Return to the previous page.
Decrements pageIndex (page number index).
pageIndex--;
if(pageIndex < 0) pageIndex = 0;
If you decrement at the very beginning, it will become negative, so make it 0.

b2.addEventListener("click", () =>
Go to the next page.
Decrement pageIndex (page number index).
pageIndex++;
if(pageIndex >= pageMax)pageIndex = pageMax - 1;
If you increment it at the very end, it will exceed the last element index, so you should make it "last page - 1".

async function displayScreen()
By adding async, the function will return a Promise object.
await task1();//Image
await task2();//Story
await task3();//Page number
await task4();//Button display toggle
await suspends processing until the state of the Promise object is determined.

return new Promise(resolve =>
The Promise function has two arguments.
The first is the method to execute.
The second allows you to set a method to handle errors, but this is optional and is not used in this sample.
By executing the first method, you can notify the Promise function that processing has finished.

resolve();
This means that the processing of this Promise function will end by executing the method with the same name as the argument.
If a method is set in this first argument, the processing of the Promise function will end as soon as the processing of that method is finished.
If an error occurs during the process, it is possible to handle the problem according to the specifications by executing the error detection process of the second argument.

[Acknowledgements]
images used are from "illustration by nawmin.com"
Thank you very much.
[URL]illustration by nawmin.com
URL[https://nawmin.stores.jp][click to open the homepage])


back



著作権情報
ホームページおよプリ等に掲載されている情報等については、いかなる保障もいたしません。
ホームページおよびアプリ等を通じて入手したいかなる情報も複製、販売、出版または使用させたり、
または公開したりすることはできません。
当方は、ホームペーよびアプリ利用したいかなる理由によっての障害等が発生しても、
その結果ホームページおよびアプリ等を利用された本人または他の第三者が被った損害について
一切の責任を負わないものとします。