Last active
April 22, 2017 20:03
-
-
Save ptomato/4973bb71c153c9109774b2392e8d22c3 to your computer and use it in GitHub Desktop.
The Mad Scientist Review - GJS Promise example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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