Skip to content

Instantly share code, notes, and snippets.

@ptomato
Last active April 22, 2017 20:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ptomato/4973bb71c153c9109774b2392e8d22c3 to your computer and use it in GitHub Desktop.
Save ptomato/4973bb71c153c9109774b2392e8d22c3 to your computer and use it in GitHub Desktop.
The Mad Scientist Review - GJS Promise example
const GLib = imports.gi.GLib;
const Gio = imports.gi.Gio;
function wrapPromise(obj, cancellable, asyncName, finishName, ...inArgs) {
return new Promise((resolve, reject) => {
let callerStack = new Error().stack
.split('\n')
.filter(line => !line.match(/<Promise>|wrapPromise/))
.join('\n');
obj[asyncName](...inArgs, cancellable, (obj, res) => {
try {
let results = obj[finishName](res);
resolve(results);
} catch (e) {
e.stack += '--- Called from: ---\n' + callerStack;
reject(e);
}
});
});
}
function loadContents(file, cancellable=null) {
return wrapPromise(file, cancellable, 'load_contents_async',
'load_contents_finish');
}
// -------------------------
let loop = GLib.MainLoop.new(null, false);
function cat(filename) {
let f = Gio.File.new_for_commandline_arg(filename);
loadContents(f)
.then(([ok, contents]) => {
print(contents);
})
.catch(e => {
logError(e);
})
.then(() => loop.quit());
loop.run();
}
if (ARGV.length != 1) {
printerr("Usage: gio-cat.js filename");
} else {
cat(ARGV[0]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment