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