When I try to run an asynchronous code like reading a file or sending an http request the program exit immediately before the callback get called.
Unlike JavaScript in the browser, gjs programs exit immediately when the main code is finished, in order to wait for the callbacks, we need to make the main code wait for it using GLib.MainLoop. For example sending an async http request and waiting for it will look like this:
const loop = new GLib.MainLoop(null, false);
session.queue_message(request, function(session, message) {
print('Download is done');
loop.quit();
});
loop.run();