0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

順番実行とJavaScript(jQuery)のコールバック地獄

Last updated at Posted at 2024-04-23

⭕⭕が終わったら…、❌❌が終わったら…、を入れ子の中に入れていくとインデントが深くなってしまい見づらくなり、保守が困難になってきます。

そんなとき、ワタシはこんな感じで書くようにしています。

	$.when(function(){
        $(".loading_modal").toggle(true);
		//dfd.resolve(); // 成功(続行)
		//dfd.reject(); // 失敗(中断)
		return;
	})
	.then(function(){
        var dfd = new $.Deferred;
        var ret = 処理A();
        if (ret) {
            dfd.resolve();
        } else {
            dfd.reject();
        }
		return dfd.promise();
	})
	.then(function(){
        var dfd = new $.Deferred;
        var ret = 処理B();
        if (ret) {
            dfd.resolve();
        } else {
            dfd.reject();
        }
		return dfd.promise();
	})
	.then(function(){
        var dfd = new $.Deferred;
        var ret = 処理C();
        if (ret) {
            dfd.resolve();
        } else {
            dfd.reject();
        }
		return dfd.promise();
	})
	.always(function(){
        // ファイナル処理
		$(".loading_modal").toggle(false);
	})
	;

参考としたURL
JavaScriptとコールバック地獄
https://techblog.yahoo.co.jp/programming/js_callback/

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?