String 如何在不使用回调的情况下使用Soup.SessionAsync将页面加载到字符串中

String 如何在不使用回调的情况下使用Soup.SessionAsync将页面加载到字符串中,string,webpage,gjs,String,Webpage,Gjs,我制作了一个很好的桌面,其中包括将一个页面从url加载到如下变量中 let url = 'http://localhost/page.php'; let file = Gio.file_new_for_uri(url).load_contents(null); let doc=(file[1]+"") return doc; 这在localhost上非常有用。问题是当我通过互联网访问某些东西时。每次循环访问此页面时,整个linux都会冻结1秒钟。所以我想使用异步方法。当然,我不确定这是

我制作了一个很好的桌面,其中包括将一个页面从url加载到如下变量中

    let url = 'http://localhost/page.php';
let file = Gio.file_new_for_uri(url).load_contents(null);
let doc=(file[1]+"")
return doc;
这在localhost上非常有用。问题是当我通过互联网访问某些东西时。每次循环访问此页面时,整个linux都会冻结1秒钟。所以我想使用异步方法。当然,我不确定这是否能解决我的问题,因为我不确定它是否能解决我认为它能解决的问题。但问题是,我所有的示例都是回调函数,我很难理解…函数可以工作…但结果在我使用此函数时消失…所以问题很简单: 有没有办法在getpage函数中返回mes变量

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+"";
}, 

由于这是一种异步方法,您无法访问
getpage
函数中的
mes
变量。
下面是
getpage
函数的执行顺序:

  • 创建Soup消息对象
  • 在队列消息中注册该函数,但暂时不要执行它end
    getpage
    函数
  • 此时
    mes
    变量不存在
  • 下载url时,将执行队列消息中注册的函数,并设置
    mes
    变量,但另一个作用域是
    getpage
    函数。
    这就是带有回调的异步函数的工作方式

    所以我的建议是使用一个真正的回调函数,并在其中进行处理:

    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 */
    }