Async / await not obvious in the workers


#1

Hi, this is working:

addEventListener("fetch", serverResponse);

async function serverResponse(event) {
  const body = buildBody();
  event.respondWith(new Response(body));
}

function buildBody() {
  return 'Hello world!';
}

This is not:

addEventListener("fetch", serverResponse);

async function serverResponse(event) {
  const body = await buildBody();
  event.respondWith(new Response(body));
}

async function buildBody() {
  return 'Hello world!';
}

As if the worker did not wait for my promise to return.

I tried to wrap in waitUntil.

I tried to replace my function with a fetch and got that error: FetchEvent handler did not call respondWith() before returning, but initiated some asynchronous task. That task will be canceled and default handling will occur -- the request will be sent unmodified to your origin. Remember that you must call respondWith() *before* the event handler returns, if you don't want default handling. You cannot call it asynchronously later on. If you need to wait for I/O (e.g. a subrequest) before generating a Response, then call respondWith() with a Promise (for the eventual Response) as the argument.

Which seems to be a good description of the error.

Obviously; if I don’t await, it returns a promise.

In short : do you know how do I async / await in a worker? :slight_smile:


#2

As far as I know, addEventListener does not accept functions that return promises as an argument.

If you change it to

addEventListener("fetch", event => {
  event.respondWith(serverResponse(event));
});

async function serverResponse(event) {
  const body = await buildBody();
  return new Response(body);
}

async function buildBody() {
  return 'Hello world!';
}

it should work (I just rewrote it off the top of my head, might be errors).


#3

Working perfectly. Thank you.

Do you happen to know where I can find the documentation for that ? (things like " addEventListener does not accept functions that return promises as an argument.")


#4

AFAIK there’s no API reference, but there’s a lot of examples of how to handle requests in the worker documentation https://developers.cloudflare.com/workers/writing-workers/.