auth0 / webtask-bundle

Module and CLI to bundle your code for use on https://webtask.io
28 stars 6 forks source link

Support webtasks returning promises #31

Open wearhere opened 6 years ago

wearhere commented 6 years ago

Now that Webtask runs on Node 8 and supports async/await (see https://github.com/auth0/webtask-bundle/issues/23), it would be nice to support webtasks that returned promises instead of calling callbacks.

The ideal

Such a webtask would ideally look like

module.exports = async function(context) {
  return { hello: context.query.name || 'Jeff' };
};

The status quo

The above would be equivalent to

module.exports = function(context, cb) {
  cb(null, { hello: context.query.name || 'Jeff' });
};

The compromise

I am aware that you can currently use await within webtasks, so long as you call the callback, like

module.exports = async function(context, cb) {
  const example = await Promise.resolve({
    hello: context.query.name || 'Anonymous'
  });
  cb(null, example);
};

However this has the following disadvantages compared to my ideal:

  1. Control flow: you have to call the callback every time you want to "return" rather than just using return. And every time you do so you have to pass null as the first parameter to the callback.
  2. Error handling: if code throws an exception, that exception will not be forwarded to the cb, it'll just be uncaught. By contrast, in the first example, if the webtask rejected with an error e, that would be equivalent to the webtask having called cb(e).

Drawbacks

I am aware that when webtasks accept only a single parameter, that parameter is assumed to be the callback not the context (see here), so my proposal would be a breaking change.