LoginSignup
36
37

More than 5 years have passed since last update.

AngularJSで同期のように非同期関数を書く

Posted at

AngularJSのData-bindingおかげで、ModelのObjectに変更があると、
すぐに$watchに捉えられ、Viewに反映することができます。

この特性をうまく利用すれば、非同期のものでも同期のように書けるのです。
例えば、下のように

var fooApp = angular.module('fooApp');

fooApp.controller('userCtrl', function($scope, User) {
    $scope.user = User.getUser('foo'); // 同期のようにしか見えないよね(ドヤッ
});

引き続きUser Serviceの実装を見ていきます

fooApp.factory('User', function($http) {
    return {
        getUser: function (username) {
            // 1.空きObjectを作成し
            result = {}

            $http.get('/api/user/' + username).success(function(data) {
                // 3.データ取得できたら、元のObjectに内容を追加
                angular.extend(result, data);
            });

            // 2.とりあえずObjectのPointerだけを渡す
            return result;
        }
    }
});

まとめれば、
1.うまくPointerだけを先に返し、
2.Responseが来たら、前のPointerを拾って、内容を流し込む
という手順でやると、非同期も同期のように書けるわけです。

この仕組みはAngularJSだけではなく、
ほかにData-bindingのできるフレームワークでも行けると思います。

36
37
9

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
36
37