1

Below is my function :

function openPopup() {
   var logsReceived = false;
   logsReceived = getLogs();
   console.log(logsReceived);
   if(logsReceived) // getting undefines
   {
        popup.open();// When I receive logs then I want to open my pop up to show logs.
   }
 }

function getLogs() {
   myService.getLogs(function (response) {
                $scope.logs = response.logs;
                return true;
        });
 }

I have tried like below also :

function openPopup() {
   getLogs();
   popup.open();//When i receive logs then i want to open my pop up to show logs.
 }

But problem with the above approach is my pop up gets open but I can't able to see logs because I haven't got the response from the server. When I close the popup and open the pop up again then I get to see the logs, because until then I have got the response from the server.

So what I would like to do is unless and until I get the response of logs I don't want to open pop up.

Note: I don't want to write code for pop up in getLogs function as because that function is getting call from lots of place.

Update: I am using Angular.js to display logs in pop up html. So I take response in 1 scope variable and then I run my loop on that scope variable in pop up html to display logs.

app.factory('myService', function ($resource) {
    var myService = $resource('Myservice', {}, {
        getLogs: {
            method: 'GET',
            url: '/root/getLogs',
        }
    });
    return myService;
})
halfer
  • 19,824
  • 17
  • 99
  • 186
I Love Stackoverflow
  • 6,738
  • 20
  • 97
  • 216

1 Answers1

2
  logsReceived = getLogs();
  console.log(logsReceived);
  if(logsReceived)

The problem is that logsReceived will be always undefined because assignment will be done later or even never. So you should move your popup.open() function to the method that will be invoked after async call ends.

Async mode:

 var myService = $resource('Myservice', {}, {
    getLogs: {
        method: 'GET',
        url: '/root/getLogs',
    }
});


myService.getLogs(null, function CALLBACK(serverResponse){
if (serverResponse) {
    showLogs(serverResponse.logs)
   }
});

You just need to invoke showLogs in the callback.

Drag13
  • 5,859
  • 1
  • 18
  • 42
  • So it is not possible to achieve what i want in my way? – I Love Stackoverflow Aug 01 '17 at 11:11
  • All is possible. If you want to write this code in a sync manner you can use async await syntax. But I think you will need to use babel to transpile it. Or you can rewrite your code into async manner. Just past to the $resource callback method that will check answer and show popup if needed – Drag13 Aug 01 '17 at 11:13
  • Upvoted for your kind efforts towards helping me but can you show me with the code of what you are saying please? – I Love Stackoverflow Aug 01 '17 at 11:15