[Javascript]非同期関数を同期関数っぽく呼び出す(async/await)

非同期関数を同期関数っぽく呼び出す(async/await)

<apex:page >
    <html>

        <head>

        </head>

        <body>

            <script type="text/javascript">

                function aFunc2(data) {
                    return new Promise(function(callback) {
                        setTimeout(function() {
                            callback(data * 2);
                        }, Math.random() * 1000);
                    });
                }

                async function sample_async_await() {
                    var val = 100;
                    val = await aFunc2(val);
                    console.log(val);                    // 200
                    val = await aFunc2(val);
                    console.log(val);                    // 400
                    val = await aFunc2(val);
                    console.log(val);                    // 800
                }

                sample_async_await();
                
            </script>

        </body>

    </html>
</apex:page>

結果

[Javascript]promise.then,awaitその3

promise.then,awaitその3

<apex:page >
    <html>

        <head>

        </head>

        <body>

            <script type="text/javascript">

                function resolveAfter2Seconds() {
                    return new Promise(resolve => {
                        setTimeout(() => {
                        resolve('resolved');
                        }, 2000);
                    });
                }

                const promise1 = new Promise((resolve, reject) => {
                    resolve('Success!');
                });

                async function asyncCall() {
                    console.log('calling');
                    const result = await resolveAfter2Seconds();
                    console.log(result);
                    // expected output: "resolved"
                    promise1.then((value) => {
                        console.log(value);
                        // expected output: "Success!"
                    });
                }

                asyncCall();

                const p = new Promise((res, rej) => {
                    res(1);
                })

                async function asyncReturn() {
                    return p;
                }

                function basicReturn() {
                    return Promise.resolve(p);
                }

                console.log(p);
                console.log(basicReturn());
                console.log(asyncReturn());

                console.log(p === basicReturn()); // true
                console.log(p === asyncReturn()); // false

            </script>

        </body>

    </html>
</apex:page>

結果

[Javascript]promise.then,awaitその2

promise.then,awaitその2

<apex:page >
    <html>

        <head>

        </head>

        <body>

            <script type="text/javascript">

                function resolveAfter2Seconds() {
                    return new Promise(resolve => {
                        setTimeout(() => {
                        resolve('resolved');
                        }, 2000);
                    });
                }

                const promise1 = new Promise((resolve, reject) => {
                    resolve('Success!');
                });

                async function asyncCall() {
                    console.log('calling');
                    const result = await resolveAfter2Seconds();
                    console.log(result);
                    // expected output: "resolved"
                    promise1.then((value) => {
                        console.log(value);
                        // expected output: "Success!"
                    });
                }

                asyncCall();

            </script>

        </body>

    </html>
</apex:page>

結果

[Javascript]promise.then,await

promise.then,await

<apex:page >
    <html>

        <head>

        </head>

        <body>

            <script type="text/javascript">

                function resolveAfter2Seconds() {
                    return new Promise(resolve => {
                        setTimeout(() => {
                        resolve('resolved');
                        }, 2000);
                    });
                }

                const promise1 = new Promise((resolve, reject) => {
                    resolve('Success!');
                });

                async function asyncCall() {
                    console.log('calling');
                    promise1.then((value) => {
                        console.log(value);
                        // expected output: "Success!"
                    });
                    const result = await resolveAfter2Seconds();
                    console.log(result);
                    // expected output: "resolved"
                }

                asyncCall();

            </script>

        </body>

    </html>
</apex:page>

結果

[Javascript]promiseのcatch,then

promiseのcatch,then

<apex:page>
    <html>

        <head>

        </head>

        <body>

            <script type="text/javascript">

                Promise.resolve()
                .then(() => {
                    // Makes .then() return a rejected promise
                    throw new Error('Oh no!');
                })
                .catch(error => {
                    console.error('onRejected function called: ' + error.message);
                })
                .then(() => {
                    console.log("I am always called even if the prior then's promise rejects");
                });
            </script>

        </body>

    </html>
</apex:page>

結果

[Javascript]promiseのerror

promiseのerror

<apex:page>
    <html>

        <head>

        </head>

        <body>

            <script type="text/javascript">

                Promise.resolve()
                .then(() => {
                    // Makes .then() return a rejected promise
                    throw new Error('Oh no!');
                })
                .then(() => {
                    console.log('Not called.');
                }, error => {
                    console.error('onRejected function called: ' + error.message);
                });
                
            </script>

        </body>

    </html>
</apex:page>

結果

[Javascript]promiseのthenからthen呼び出す

promiseのthenからthen呼び出す

<apex:page>
    <html>

        <head>

        </head>

        <body>

            <script type="text/javascript">

                var p2 = new Promise(function(resolve, reject) {
                resolve(1);
                });

                p2.then(function(value) {
                    console.log(value); // 1
                return value + 1;
                }).then(function(value) {
                    console.log(value + ' - A synchronous value works'); // 2 - A synchronous value works
                });

                p2.then(function(value) {
                    console.log(value); // 1
                });
                
            </script>

        </body>

    </html>
</apex:page>

結果

[Javascript]promise連鎖

promise連鎖

<apex:page>
    <html>

        <head>

        </head>

        <body>

            <script type="text/javascript">

                Promise.resolve('foo')
                // 1. Receive "foo", concatenate "bar" to it, and resolve that to the next then
                .then(function(string) {
                    return new Promise(function(resolve, reject) {
                    setTimeout(function() {
                        string += 'bar';
                        resolve(string);
                    }, 1);
                    });
                })
                // 2. receive "foobar", register a callback function to work on that string
                // and print it to the console, but not before returning the unworked on
                // string to the next then
                .then(function(string) {
                    setTimeout(function() {
                    string += 'baz';
                    console.log(string); // foobarbaz
                    }, 1)
                    return string;
                })
                // 3. print helpful messages about how the code in this section will be run
                // before the string is actually processed by the mocked asynchronous code in the
                // previous then block.
                .then(function(string) {
                    console.log("Last Then:  oops... didn't bother to instantiate and return " +
                                "a promise in the prior then so the sequence may be a bit " +
                                "surprising");

                    // Note that `string` will not have the 'baz' bit of it at this point. This
                    // is because we mocked that to happen asynchronously with a setTimeout function
                    console.log(string); // foobar
                });

                // logs, in order:
                // Last Then: oops... didn't bother to instantiate and return a promise in the prior then so the sequence may be a bit surprising
                // foobar
                // foobarbaz
                
            </script>

        </body>

    </html>
</apex:page>

結果

[Javascript]promiseのonFulfilled、onRejected

promiseのonFulfilled、onRejected

<apex:page>
    <html>

        <head>

        </head>

        <body>

            <script type="text/javascript">

                const resolvedProm = Promise.resolve(33);

                let thenProm = resolvedProm.then(value => {
                    console.log("this gets called after the end of the main stack. the value received and returned is: " + value);
                    return value;
                });
                // instantly logging the value of thenProm
                console.log(thenProm);

                // using setTimeout we can postpone the execution of a function to the moment the stack is empty
                setTimeout(() => {
                    console.log(thenProm);
                });
                
            </script>

        </body>

    </html>
</apex:page>

結果

[Javascript]promiseのthen,reason

promiseのthen,reason

<apex:page>
    <html>

        <head>

        </head>

        <body>

            <script type="text/javascript">

                const promise1 = new Promise((resolve, reject) => {
                resolve('Success!');
                });

                promise1
                .then((value) => {
                    console.log(value);
                    // expected output: "Success!"
                }
                ,reason => {
                    console.log("Error!");
                });
                
            </script>

        </body>

    </html>
</apex:page>