Skip to content Skip to sidebar Skip to footer

Angularjs And Q.fcall

Angulars $q is a promise/deferred implementation inspired by Kris Kowal's Q. In Q, you create a promise with var myPromise = Q.fcall(myFunction); Here the myFunction will be invok

Solution 1:

Are you looking for something like this

functiondoWorkAsync() {
   var defer = $q.defer();
   //do some work async and on a callback asyncWork(function(data)) {
      defer.resolve(data);
   }
   return defer.promise;
}

Now you call this function

doWorkAsync().then(function(data));

Number of angularJS library function already return a promise on invocation. Like $timeout,$http, $resource.

Solution 2:

I don't know if this is very smart, but it works for me:

functionfcall(someValues) {
    var deferrd = $q.defer();
    deferrd.resolve(someValues);
    return deferrd.promise;
}

fcall(123).then(function(values) {
    console.log(values); // 123
});

Solution 3:

Ok, cleaner alternative is injecting Angular's $timeout and let's say again that function myFunction is the work I want to do asynchroniously, I'll just do:

functiondoWorkAsync() {
   return$timeout(myFunction, 10);
}

and doWorkAsync will return a promise that will be resolved when myFunction has finished it's work.

For unit testing I can call $timeout.flush() to fire the timeout function instantly.

Solution 4:

functioncreatePromise(func) {
        returnfunction (params) {
            var deferred = $q.defer();

            $timeout(function () {
                try {
                    var rtn = func(params);
                    deferred.resolve(rtn);
                }
                catch (ex) {
                    deferred.reject();
                }

            })
            return deferred.promise
        }
    }

Solution 5:

You can use $q as a constructor similar to how ES6 works.

functionasyncGreet(name) {
  return$q(function(resolve, reject) {
    resolve('Hello, ' + name + '!');
  });
}

angular docs

Post a Comment for "Angularjs And Q.fcall"