Ext JS 4 の Ext.Ajax.request で同期通信する

最近、業務でExt JSを使ってまして。
サーバとはExt.Ajax.requestを使って非同期に通信してるのだけど、同期でしたいときもあるわけです。


Ext.Ajax.requestのオプションで指定できるかと思ったけど、APIドキュメントでは見つからず。
さらにフォーラムで開発チームの人が

As has beeb mentioned many times. Synchronous operation is neither supported nor desirable. Use callbacks to continue processing after the return of data.
How to make synchronous AJAX request using Ext library?

って言ってて、無いものだと諦めかけてたのです。

それ、async: falseで出来るよ

です。
ソース*1を見てみると、asyncというパラメータをXMLHttpRequest.openの第3引数に渡してて、それはどうやらオプションから取得しているみたい*2
ので実際にasync: falseを指定してやると同期通信になった。

注意

古いバージョンは見てないので、元々あったのか新しく加わったのかは分からないです。
バージョンを固定するのでなければあんまり使わないほうがよいかも。

                                                                                                      • -


以下は検証時のソース*3
Ext.Ajax.requestでasync: falseを指定し、test.php(5秒スリープするだけ)にPOSTでアクセスするだけ。
結果が帰ってきて、コールバックの実行が終わるまで、他の操作は行えなかった。
@test.html

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>test</title>
        <link rel="stylesheet" type="text/css" href="../ext-4.0.2a/resources/css/ext-all-gray.css"  />
        <script type="text/javascript" src="../ext-4.0.2a/bootstrap.js" ></script>
        <script type="text/javascript">
            Ext.onReady(function() {

                btn1 = Ext.create('Ext.button.Button', {
                    renderTo: 'btn1'
                });

                btn1.on('click', function() {
                    Ext.Ajax.request({
                        url: 'test.php',
                        method: 'POST',
                        async: false,    // <- ここ
                        success: function () {
                            alert('done!');
                        }
                    })
                });
            });
        </script>
    </head>
    <body>
        <div id="btn1"></div>
    </body>
</html>

@test.php

<?php

sleep(5);

*1:4.0.7(GPL版)

*2:デフォルトはtrue

*3:職場だったので4.0.2だけど多分大丈夫…!