0

I've made a nice desklet which among other things load a page from a url into a variable like this

    let url = 'http://localhost/page.php';
let file = Gio.file_new_for_uri(url).load_contents(null);
let doc=(file[1]+"")
return doc;

This work great on localhost. the problem is when i acces something over the internet. entire linux freeze for like 1 sec every time the loop acces this page. So i was thinking to use the async method. Of course im not sure if this will solve the problem for me cause im not very sure it does what i think it does.But the problem is that all my examples are with callbacks which im having a hard time to understand...the function works...but the result vanish the moment im done with this function..so question is simple: Is there any way to return the mes variable in the getpage function?

getpage: function() {
  let url = 'http://localhost/page.php';
  let message = Soup.Message.new('GET', url)
_httpSession.queue_message(message, function(session, message) {
  let mes = message.response_body.data;
  });
  //like thie 
  return mes+"";
}, 

1 Answers1

0

As it's an async method, you can't have access to the mes variable in the getpage function.
Here is the execution order of the getpage function:

  1. creation of the Soup Message object
  2. register the function in queue message, but don't execute it for the moment end getpage function.
  3. At this point mes variable doesn't exist

When the url will be downloaded, the function registered in the queue message will be executed and the mes variable will be set, but in another scope that the getpage function.
That's the way async functions with callbacks work.

So my suggestion is to use a real callback function and to do your treatments in it:

getpage: function() {
  let url = 'http://localhost/page.php';
  let message = Soup.Message.new('GET', url)
  _httpSession.queue_message(message, real-callback);
},

real-callback: function(session, message) {
  let mes = message.response_body.data;
  /* do here what you wanted to do at the end of getpage fonction */
}
Nicolas
  • 6,289
  • 4
  • 36
  • 51