| async/awaitの関係(基本) |
| async/awaitの基本的な処理の説明をします。 |
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);
});
| 実行順番 | 処理内容 |
| STEP 1 | copyButtonボタンをタップしたイベントにより copyToClipboardメソッドを実行します。 |
| STEP 2 | try〜catchの構文を実行します。 |
| STEP 3 | awaitはPromiseの解決(または拒否)を待つために使われています。 これにより直感的に非同期処理の結果をまるで同期処理のように扱うことができます。 awaitの結果 [OK] 「navigator.clipboard.writeText」を処理します。 [NG] catchの処理を実行します。 |
| STEP 4 | awaitの結果(Navigator APIの「writeText」)をPromiseとしてasyncに返します。 |
| Async/await relationship (basics) |
| This section explains the basics of async/await. |
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);
});
| Execution order | Processing contents |
| STEP 1 | The copyToClipboard method is executed when the copyButton button is tapped. |
| STEP 2 | Executes the try-catch syntax. |
| STEP 3 | await 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 4 | The result of await (Navigator API's "writeText") is returned to async as a Promise. |
| ホームページおよプリ等に掲載されている情報等については、いかなる保障もいたしません。 ホームページおよびアプリ等を通じて入手したいかなる情報も複製、販売、出版または使用させたり、 または公開したりすることはできません。 当方は、ホームペーよびアプリ利用したいかなる理由によっての障害等が発生しても、 その結果ホームページおよびアプリ等を利用された本人または他の第三者が被った損害について 一切の責任を負わないものとします。 |