Newer
Older
2024-Tsubasa / system / js / async_await.html
@tsubasa tsubasa on 30 Jul 2024 2 KB add: test file
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>async / await</title>
</head>

<body>
    <p>async / await</p>
    <script>
        // async function myFunction() {
        //     return "Hello";
        // }

        // // 呼び出し
        // myFunction().then(result => console.log(result)); // "Hello" ここがPromise要素

        // ----------------------------------------------------

        // async function myFunction() {
        //     let result = await Promise.resolve("Good, Morning");
        //     console.log(result); // "Hello"
        // }

        // myFunction();

        // ----------------------------------------------------

        // async function fetchData() {
        //     try {
        //         let response = await fetch('../package.json');
        //         if (!response.ok) { // response.okはステータスコードが200-299の範囲内ならtrue, それ以外ならfalse
        //             throw new Error('Network response was not ok');
        //         }
        //         let data = await response.json(); // responseをperseしてPromiseを返す
        //         console.log(data);
        //     } catch (error) {
        //         console.error('Fetch error:', error);
        //     }
        // }

        // fetchData();

        // ----------------------------------------------------

        // async function fetchMultipleData() {
        //     try {
        //         let [data1, data2] = await Promise.all([
        //             fetch('../package.json').then(response => response.json()),
        //             fetch('../package-lock.json').then(response => response.json())
        //         ]);
        //         console.log(data1, data2);
        //     } catch (error) {
        //         console.error('Fetch error:', error);
        //     }
        // }

        // fetchMultipleData();

        // ----------------------------------------------------

        // async function processArray(array) {
        //     for (let item of array) {
        //         let result = await someAsyncFunction(item);
        //         console.log(result);
        //     }
        // }

        // processArray([1, 2, 3]);

        // ----------------------------------------------------

        async function myFunction() {
            try {
                let result = await someAsyncFunction();
                console.log(result);
            } catch (error) {
                console.error('Error:', error);
            }
        }

        myFunction();
    </script>
</body>

</html>