logo
down
shadow

Can I use $q.all in AngularJS with a function that does not return a .promise?


Can I use $q.all in AngularJS with a function that does not return a .promise?

By : Osman
Date : November 22 2020, 11:12 AM
I wish this helpful for you $q.when is used in scenarios where you don't know upfront whether the function is returning a promise or a direct value.
The following example/plunker shows a method, whose result is used in $q.all, and which returns different type of object (int or promise) every time it's called:
code :
app.controller('MainController', function($scope, $q, $http) {
  var count = 0;

  function doTask1() {
    var defer = $q.defer();
    $http.get('abc.json')
      .success(function (data) {
        defer.resolve(data);
      })
      .error(function () {
        defer.reject();
      });

    return defer.promise;
  }

  /**
   * This method will return different type of object 
   * every time it's called. Just an example of an unknown method result.
   **/
  function doTask2() {
    count++;
    var x = 99;
    if(count % 2){
      console.log('Returning', x);
      return x;
    } else {
      var defer = $q.defer();
      defer.resolve(x);
      console.log('Returning', defer.promise);
      return defer.promise;
    }

  }

  $scope.fetchData = function(){

    // At this point we don't know if doTask2 is returning 99 or promise.
    // Hence we wrap it in $q.when because $q.all expects 
    // all array members to be promises
    $q.all([
      $q.when(doTask1()),
      $q.when(doTask2())
    ])
      .then(function(results){
        $scope.results = results;
      });

  };

});
<body ng-app="myApp" ng-controller='MainController'>
  <button ng-click="fetchData()">Run</button>
  <pre>{{results|json}}</pre>
</body>


Share : facebook icon twitter icon
How can I return a promise from a function that calls a $http.get in AngularJS?

How can I return a promise from a function that calls a $http.get in AngularJS?


By : NDOTNET
Date : March 29 2020, 07:55 AM
like below fixes the issue Easy, you return a promise yourself. You need to inject $q for this (take a look at the docs for more information).
Then you can update your code to:
code :
getX: function ($scope) {
    var defer = $q.defer();
    $http.get('/api/X/GetSelect').success(function (data) {
        ...
        ...
        defer.resolve();
    }).error(function (data) {
        ...
        defer.reject();
    });
    return defer.promise;
}
Return value of a promise to a function in AngularJS

Return value of a promise to a function in AngularJS


By : user2457938
Date : March 29 2020, 07:55 AM
With these it helps You should change the way you think about things when you work with asynchronous code. You no longer return values, instead you use Promise or callback patterns to invoke code when data becomes available.
In your case your factory can be:
code :
.factory('dataService', function($http, $log, $q) {
    return {
        getTeacher: function(teacher) {
            // Originally this was a jsonp request ('/teacher/' + teacher)
            return $http.get('http://echo.jsontest.com/key/value/one/two').then(function(response) {
                return response.data;
            }, function() {
                $log.error(msg, code);
            })
        }
    };
});
dataService.getTeacher('Lanc').then(function(data) {
    $scope.teacher = data;
});
AngularJS - return promise success value to the calling function

AngularJS - return promise success value to the calling function


By : Jasinthar Amir
Date : March 29 2020, 07:55 AM
it helps some times The current value of user being a promise is correct. Once the promise gets resolved, it will be assigned to the data returned on success.
But you have to be careful when reassigning objects or arrays. See Service variable not updating in controller
code :
$scope.grantRole = function(user) {

  Auth.grantRole(user).then(
    function success(data){
        angular.copy(data, user);
    },
    function error(err){
        console.log(err);
    }
);
How can I return an AngularJS promise from a function return?

How can I return an AngularJS promise from a function return?


By : olafur
Date : March 29 2020, 07:55 AM
it fixes the issue I have this Typescript / Javascript function: , Your wordFormRowClicked function must return a promise:
code :
var _this = this;
wordFormRowClicked = function (wf) {
    var self = _this;
    var promises = [];
    if (_this.wordFormIdentity != wf.wordFormIdentity) {
        angular.forEach(self.word.wordForms, function (wf, key) {
            var wordFormNgForm = 'wordFormNgForm_' + wf.wordFormIdentity;
            if (self[wordFormNgForm].$pristine) {
                ;
            }
            else {
                var updatePromise = self.wordFormUpdate(wf).then(function () {
                    return self[wordFormNgForm].$setPristine();
                });
                promises.push(updatePromise);
            }
        });

    }
    return $q.all(promises);
};
wordFormRowClicked.then(function () {
    //at this point all promises are resolved
    this.wordFormIdentity = wf.wordFormIdentity;
});
How can I return an AngularJS promise from a simple function?

How can I return an AngularJS promise from a simple function?


By : prabbide
Date : March 29 2020, 07:55 AM
Hope this helps My code is doing this: , Assuming wordFormUpdate is promise:
code :
wordFormRowClicked = (wf): ng.IPromise<any> => {
    var self = this;
    if (this.wordFormIdentity != wf.wordFormIdentity) {
        return self.wordFormUpdate(wf);
    }
}
wordFormRowClicked(someParam).then(() => {
    this.wordFormIdentity = wf.wordFormIdentity;
});
Related Posts Related Posts :
  • How to fix "Object is possibly undefined"?
  • How can one use TensorFlow.js tf.data.generator for remote data sources since generators can't use callbacks
  • How can I unescape a string from python using javascript
  • How to add days into my date using angular pipe?
  • Keydown not firing on page loaded in <object> element
  • Refetch queries in react-native with graphql
  • How to execute functions across objects identically to executing the function itself with a this reference
  • NGRX Effect withLatestFrom Typescript error ts2345 troubleshooting
  • Make a checkbox checked if its id is present in an array
  • Remove disabled class when response code is 1 in each element javascript
  • Creating an input select in an editable form
  • How to convert string of ASCII codes to string of characters?
  • Detect system time and set css animation start time in browser
  • How can I build a dataTable, with a dropbox filter on top, calculated on backend?
  • What needs to be done to make multiple screen support for Javascript happen?
  • How to format a full year date/time
  • this.props.match.params passed into child component after authorisation
  • Highcharts: create multiple series grouped my month and year using JSON data
  • JS: Keep variable values for onclick event attached inside for loop
  • Failed prop type. Required prop types are undefined in my redux store
  • How to not import Vue in main js and store
  • Javascript make table with rows and columns given by user and change each cells colour onclick
  • How do you fix "ERROR in Path must be a string. Received undefined" in webpack4/copy-webpack-plugin
  • Protractor Fetching Email with Mail Listener: TypeError: deferred.fulfill is not a function
  • date-time picker bootstrap Tempus Dominus
  • How do I get all radio button id's via the name
  • Using d3 in for loop
  • Impact an array of objects
  • JS split string and return index of each split
  • Javascript/JS - Referring to classes and variables dynamically within a change event loop
  • Query a specific GET field?
  • Mapping multiple form inputs of the same name into a JavaScript object
  • How can I not to return a field from object in JavaScript?
  • Creating and testing a single Javascript nested function
  • Formatting server side jQuery Datatable
  • How to show tooltips onmouseover in p:calendar
  • typescript - calling function at random intervals in ionic
  • Correct way to populate an array from a promise
  • JavaScript Mini-Max Sum - Returns 0
  • canvas not clearing while radius of circle decreasing..?
  • Dynamically Growing Dropdown Component with clickoutside directive
  • MultichoiceField in ModelForm for Django with DB relations
  • React Native "if" statement behaviour? Early exit or full evaluation?
  • Call Jquery function on Input tag having data-slider
  • How to process negative shifts in Caesars Cipher (Javascript)
  • Animating Line position in Konva
  • Why a state is not resolved as a variable in nextjs
  • How to efficiently evaluate element in javascript array by using reduce function
  • Google script web app goes blank page after submit
  • Event for the load-end of dynamically added CSS files through innerHTML
  • How to retrieve some text from a sibling div element in jQuery
  • How to display half star rating in my following custom angular star rating example?
  • Angular 8: ternary operation for img src attribute?
  • Is this proper JS for this J-Query expanding textArea? Is 'this' the same as event.target in JS also?
  • How to fix user fetching from a collection in discord.js?
  • Can I create an item id when adding it to a collection?
  • Temporarily disable a specific option after it has been selected (in any selector) for all instances of that selector in
  • Vis.js timeline item align property not working
  • How to select one element instead of all elements using 'clicked' in a Django for loop
  • How to check if 2 <img> tags contain the same image
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org