0

I have setup a proxy to "promisify" callbacked functions like this:

const browser = new Proxy({}, {
    get: function(target, name, receiver) {
        return function(...args) {
            if (userExpectsPromise) { // how to detect this?
                return new Promise(resolve => chrome[name](...args, resolve))
            } else {
                return chrome[name](...args);
            }
        };
        return target[name];
    }
});

What this does is allows user to do browser.***('arg1', 'arg2'), this will call *** on the chrome branch.

However some of the *** on chrome branch accept a final argument of a callback. When it does, a user adds a .then so they would do - browser.***('arg1', 'arg2').then(.....). I need to detect/intercept if user did a .then. Is this possible?

My other option would be to hardcode which chrome.*** accept a callback, but that is not safe way, as the chrome.*** API is always evolving.

Noitidart
  • 35,443
  • 37
  • 154
  • 323
  • 1
    I'll remove my comments, just realised you're using `new Proxy` - something I've not used before - reading documentation now (I like the look of this proxy thing!) – Jaromanda X Apr 23 '17 at 02:01
  • Thank you brother @JaromandaX ! :) – Noitidart Apr 23 '17 at 02:04
  • one thing ... `return target[name];` is unreachable code – Jaromanda X Apr 23 '17 at 02:21
  • I don't think you need any special handling ... just always `return chrome[name](...args);` - because if `chrome[name]` is function that is expected to return a promise, it will return a promise – Jaromanda X Apr 23 '17 at 02:24
  • 1
    hmmm, perhaps I misunderstand the requirement now that I look closely at your code - are you trying to "promisify" a function that uses a callback in the case of the "user" using `.then` on the proxied call? – Jaromanda X Apr 23 '17 at 02:44
  • Yes sir! Exactly! I couldn't think of that word! `promisify` is what I'm trying to do! haha – Noitidart Apr 23 '17 at 03:27
  • 1
    I don't think there's a reliable way to do this, because the only way I can think of doing it relies on the number of arguments passed in to the "proxy" being one less than expected by the proxied function - and since javascript functions can be called with any number of arguments, regardless of how many are "declared" in the definition, this isn't reliable at all - and you can't tell, on the call of a function, if there's a `.then` afterwards – Jaromanda X Apr 23 '17 at 03:31
  • Thanks @JaromandaX for your help - heah I'm stumped too, I'm researching Reflect right now - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/ – Noitidart Apr 23 '17 at 04:25

0 Answers0