gjs 中的异步代码在调用回调之前退出

Asynchronous code in gjs exit before the callback get called

当我尝试 运行 异步代码(例如读取文件或发送 http 请求)时,程序会在调用回调之前立即退出。

与浏览器中的JavaScript不同,gjs程序在主代码完成后立即退出,为了等待回调,我们需要让主代码等待它使用GLib.MainLoop .例如发送异步 http 请求并等待它看起来像这样:

const loop = new GLib.MainLoop(null, false);

session.queue_message(request, function(session, message) {
    print('Download is done');
    loop.quit();
});

loop.run();