1
0

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 1 year has passed since last update.

ASP.NETのPageMethodsをasync/awaitで書く

Posted at

ASP.NETで開発をしている人は、.aspx.vbのWebMethodをjs側のPageMethodsで呼び出して使用している人もいるかと思います。しかし、コールバック処理中にさらにPageMethodsでコールバックを行うと、皆さんご存知のコールバック地獄に陥ってしまいます……。令和ですし、もうIE向けに開発する心配もありませんので、async/awaitを使用してPageMethodsを呼んじゃいましょう。

PageMethodsAsync

function PageMethodsAsync(functionName, ...args) {
    return new Promise((resolve, reject) => {
        PageMethods[functionName](...args,
            result => {resolve(result)},
            error => {reject(error)}
        );
    });
}

このコードを使用すれば、コールバック地獄から抜け出すことができます!元々あったPageMethodsをPromiseでラップしています。第一引数にWebMethodの関数名、第二引数以降に渡したい引数を書きます。

使用例

// 旧
function InputCheck() {
    // ボタンを押したときの入力チェック
    const val1 = $get('val1');
    const val2 = $get('val2');
    PageMethods.InputCheck(val1,
        function(result) {
        // 成功時処理
            PageMethods.InputCheck2(val2,
                function(result) {
                    // 成功時処理
                }
            )
        }
    )
}

// 新
async function InputCheck() {
    // ボタンを押したときの入力チェック
    const val1 = $get('val1');
    const val2 = $get('val2');
    const result = await PageMethodsAsync("InputCheck", val1);
    const result2 = await PageMethodsAsync("InputCheck2", val2);
    // この後に成功時処理
}

これでサーバーからの処理を待てるし、ネストも減りました!やったー!

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?