diff options
author | Sergio Costas <rastersoft@gmail.com> | 2022-02-26 19:55:25 +0100 |
---|---|---|
committer | Sergio Costas <rastersoft@gmail.com> | 2022-03-28 16:59:23 +0200 |
commit | 7087f0501141a3dbaa87caffebdaf67aa4ddc16d (patch) | |
tree | cd1ea7eb035e855560073c5a0e382b1a509ebd99 | |
parent | 46c761e9196fc01fd6622196297a6446a5a999e3 (diff) | |
download | gjs-7087f0501141a3dbaa87caffebdaf67aa4ddc16d.tar.gz |
Add support for async calls in DBusProxyWrapper
Currently, DBusProxyWrapper dynamically creates two methods for
each method available in the DBus interface: one with the suffix
Sync (which blocks the calling thread until the call returns),
and another with the suffix Remote (which accepts a callback,
called when the DBus calls returns).
Since GJS has support for async/await, it is a good idea to use
them for DBus. Unfortunately, that means creating some plumbing
using Promises. It is not complex, but it is a repetitive task.
This MR fixes this by adding a third method, suffixed with
Async, that returns a Promise that calls the DBus method and
returns the result with `resolve` (or `reject` if an error
occurs). This allows to call a DBus method from an async
function and wait for the result using `await`.
-rw-r--r-- | installed-tests/js/testGDBus.js | 13 | ||||
-rw-r--r-- | modules/core/overrides/Gio.js | 16 |
2 files changed, 28 insertions, 1 deletions
diff --git a/installed-tests/js/testGDBus.js b/installed-tests/js/testGDBus.js index 78907e48..88c5831b 100644 --- a/installed-tests/js/testGDBus.js +++ b/installed-tests/js/testGDBus.js @@ -407,6 +407,19 @@ describe('Exported DBus object', function () { loop.run(); }); + async function testAsync(value) { + let result = await proxy.nonJsonFrobateStuffAsync(value); + return result; + } + + it('can call a remote method using AWAIT', function () { + testAsync(1).then(result => { + expect(result[0]).toEqual('Oops'); + loop.quit(); + }); + loop.run(); + }); + it('can call a remote method with no in parameter', function () { proxy.noInParameterRemote(([result], excp) => { expect(result).toEqual('Yes!'); diff --git a/modules/core/overrides/Gio.js b/modules/core/overrides/Gio.js index be2e5247..6cc29b17 100644 --- a/modules/core/overrides/Gio.js +++ b/modules/core/overrides/Gio.js @@ -185,8 +185,22 @@ function _addDBusConvenience() { let i, methods = info.methods; for (i = 0; i < methods.length; i++) { var method = methods[i]; - this[`${method.name}Remote`] = _makeProxyMethod(methods[i], false); + let remoteMethod = _makeProxyMethod(methods[i], false); + this[`${method.name}Remote`] = remoteMethod; this[`${method.name}Sync`] = _makeProxyMethod(methods[i], true); + this[`${method.name}Async`] = function (...args) { + return new Promise((resolve, reject) => { + args.push((result, error, fdList) => { + if (error) + reject(error); + else if (fdList) + resolve([result, fdList]); + else + resolve(result); + }); + remoteMethod.call(this, ...args); + }); + }; } let properties = info.properties; |