balaji balaji

balaji balaji

  • NA
  • 14
  • 996

Angularjs Chaining Promises and $q

Apr 29 2019 5:41 AM
while executing the code alert("promiseC done") is displaying first and then alert("promiseC"); is displaying last because of this the data was not displaying properly from function Displaydata(); from below code.
  1. App.controller("Ctrl"function ($scope, $http, $location, $window, $sce, $q) {  
  2. var promiseA = getMA(Id).then(function () {  
  3. alert("GOT MA data from API call");  
  4. // doing some stuff with MA data ...  
  5. }  
  6. var promiseB = getMB(Id).then(function () {  
  7. alert("GOT MB data from API call");  
  8. // doing some stuff with MBdata ...  
  9. }  
  10. var promiseC = getMC(Id).then(function () {  
  11. alert("GOT MC data from API call");  
  12. // doing some stuff with MC data ...  
  13. getotherdata(MC.Id).then(function () {  
  14. . .  
  15. }  
  16. ..  
  17. alert("promiseC");  
  18. }  
  19. var promiseB = promiseA.then(function (result) {  
  20. alert("promiseA done");  
  21. });  
  22. var promiseC = promiseB.then(function (result) {  
  23. alert(" promiseB done");  
  24. });  
  25. var promiseD = promiseC.then(function (result) {  
  26. alert("promiseC done"); Displaydata();  
  27. });  
  28. }  
How can i make to work properly so that alert("promiseC") will display first and then alert("promiseC done").
 
Also tried in below way but same issue as above in chain promises.
  1. var promiseA = function(){  
  2. var deferedA = $q.defer();  
  3. deferedA.resolve();  
  4. return deferedA.promise;  
  5. }  
  6. var promiseB = function(){  
  7. var deferedB = $q.defer();  
  8. deferedB.resolve();  
  9. return deferedB.promise;  
  10. }  
  11. var promiseC = function(){  
  12. var deferedC = $q.defer();  
  13. alert("promise c");  
  14. deferedC.resolve();  
  15. return deferedC.promise;  
  16. }  
  17. $q.all([promiseA, promiseB, promiseC]).then(function () {  
  18. alert("all done"); Displaydata();  
  19. })  

Answers (3)