[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>

結果

投稿者: kinkun

保有資格 Salesforce Certified Platform App Builder T Salesforce Certified Platform Developer I Salesforce Certified Platform Developer II Salesforce Certified Administrator

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です