Promises in async methods

I have seen in the notes from the TPAC meeting that promises in async
methods were brought up:
https://browserext.github.io/minutes/2016-09-22.html#item02

Since I wasn't there, I'd like to follow up here. We (Adblock Plus) would
love to see a browser extension API that natively supports promises, though
as long as some supported browsers still expect callbacks it wouldn't make
anything easier for us. But it seems that the Chromium team is also
considering using promises:
https://bugs.chromium.org/p/chromium/issues/detail?id=328932

As for compatibility with the existing Chrome extension API, I think that
won't be an issue. We could just have methods take an optional callback and
return also promise. IMO this would make more sense than a separate
namespace or a new manifest option/version.

However, the only problem I see, is that some methods, currently do some
internal optimizations if the callback is omitted, e.g. if you send a
message and there is no callback for the response, Chrome immediately
closes the internal port. Those kind of optimizations would be impossible
if a promise is returned, which might or might not be used later. Though
I'm not sure how significant those optimizations are, and if necessary, I
guess, we could still keep using callbacks for the few APIs where it makes
sense for performance reasons, while using promises for most methods.

Also, I'd like to point out, that in addition to have async methods return
a promise, it would be great if message responders could deal with
promises, so that instead of:

  browser.runtime.onMessage.addListener(function(message, sendResponse)
  {
    if (message == "get-foo")
    {
       browser.storage.local.get("foo", function(items)
       {
         sendResponse(items.foo);
       });
       return true;
    }
    return false;
  });

One could write:

  browser.runtime.onMessage.addListener(function(message)
  {
    if (message == "get-foo")
    {
       return browser.storage.local.get("foo").then(items => items.foo);
    }
  });

Or perhaps even better, to have the extension API dispatch the messages:

  browser.runtime.onMessage.addListener("get-foo", function(message)
  {
    return browser.storage.local.get("foo").then(items => items.foo);
  });

Sebastian

Received on Tuesday, 4 October 2016 14:07:03 UTC