戻る

async/awaitの関係(基本)
async/awaitの基本的な処理の説明をします。

async/await(コピーのサンプル)
copy
const copyButton = document.getElementById("copyButton");
const textToCopy = "コピーしたいテキスト";

async function copyToClipboard(text) 
{
	try 
	{
		await navigator.clipboard.writeText(text);
		console.log("テキストがクリップボードにコピーされました");
	} catch (err) {
		console.error("クリップボードへのコピーに失敗しました: ", err);
	}
}

copyButton.addEventListener("click", () => 
{
	copyToClipboard(textToCopy);
});

Promiseを使用して非同期処理を実装しています。
この例ではコピーの結果(成功か失敗か)をPromiseとして受け取っています。
実行順番処理内容
STEP 1copyButtonボタンをタップしたイベントにより
copyToClipboardメソッドを実行します。
STEP 2try〜catchの構文を実行します。
STEP 3awaitはPromiseの解決(または拒否)を待つために使われています。
これにより直感的に非同期処理の結果をまるで同期処理のように扱うことができます。
awaitの結果
[OK]
「navigator.clipboard.writeText」を処理します。
[NG]
catchの処理を実行します。
STEP 4awaitの結果(Navigator APIの「writeText」)をPromiseとしてasyncに返します。

Promiseやasync/awaitの将来的な位置付け
PromiseはJavaScriptにおける非同期処理の基幹ともいえる仕組みであり、ES6(ECMAScript 2015)から標準化されています。
async/awaitはその上に構築された構文です。


戻る
back

Async/await relationship (basics)
This section explains the basics of async/await.

async/await (copy example)
copy
const copyButton = document.getElementById("copyButton");
const textToCopy = "The text you want to copy";

async function copyToClipboard(text) 
{
	try 
	{
		await navigator.clipboard.writeText(text);
		console.log("The text has been copied to the clipboard");
	} catch (err) {
		console.error("Copying to clipboard failed: ", err);
	}
}

copyButton.addEventListener("click", () => 
{
	copyToClipboard(textToCopy);
});

Asynchronous processing is implemented using Promise.
In this example, the copy result (success or failure) is received as a Promise.
Execution orderProcessing contents
STEP 1The copyToClipboard method is executed when the copyButton button is tapped.
STEP 2Executes the try-catch syntax.
STEP 3await is used to wait for the Promise to resolve (or reject).
This allows you to intuitively treat the results of an asynchronous process as if it were a synchronous process.
Results of await
[OK]
Processes "navigator.clipboard.writeText".
[NG]
Executes the catch process.
STEP 4The result of await (Navigator API's "writeText") is returned to async as a Promise.

Future Position of Promise and async/await
Promise is the core mechanism for asynchronous processing in JavaScript, and has been standardized since ES6 (ECMAScript 2015).
async/await is a syntax built on top of it.


back



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