4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

非同期な自動再試行をネイティブのPromiseを用いて実装

Last updated at Posted at 2015-04-14

…できてるのかどうか分からないんだけど、用途を絞っちゃう場合はこんな感じでいいの?

3000ミリ秒後にコンソールに出力される例
<!DOCTYPE html>
<html>
    <head>
        <script>
            var RetryableQuerySelector = function self(selector, maxRetries, delay) {
                return new Promise(function (resolve) {
                    var element = document.querySelector(selector);
                    if (element) {
                        resolve(element);
                    } else if (maxRetries-- > 0) {
                        setTimeout(function () {
                            self(selector, maxRetries, delay).then(function (element) {
                                return resolve(element);
                            });
                        }, delay);
                    } else {
                        console.error('Failed to select: ' + selector);
                    }
                });
            };
            RetryableQuerySelector('div', 5, 1000).then(function (element) {
                console.log(element);
            });
            setTimeout(function () {
                document.body.appendChild(document.createElement('div'));
            }, 3000);
        </script>
    </head>
    <body>
    </body>
</html>

もっと一般的な実装の仕方がよく分からないので、詳しい方おられましたらコメントや編集リクエストお願いします…

書きました

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?