Should I use event.waitUntil() or await fetch() or just fetch()?


#1

Please see the code below:

const res = await fetch(request);
if (res.status === 404) {
     return new Response('', { status: 404, headers: { 'Location': 'https://go.tallyfy.com/404.html' } });        	
}
else {
     return res;
}

Would this actually be the right way of doing it, instead?

const res = event.waitUntil(fetch(request));
if (res.status === 404) {
     return new Response('', { status: 404, headers: { 'Location': 'https://go.tallyfy.com/404.html' } });        	
}
else {
     return res;
}

There’s nothing else I want to do other than to fetch the response from the origin, check it’s a 404 or not and then proceed to finish.


#2

Or perhaps, is this the correct blocking way to do this?

const res = fetch(request);
if (res.status === 404) {
	return new Response('', { status: 404, headers: { 'Location': 'https://go.tallyfy.com/404.html' } });        	
}
else {
	return res;
}

#3

Hi @tallyfy,

const res = await fetch(request) is the correct version. fetch() returns a promise for a response – to get the actual response, it must either be awaited or have .then() called on it, like fetch(request).then(response => { if response.status === 404) ... }. Using await is typically the more natural of the two options, as the code turns out easier to read.

event.waitUntil() is only useful if you have some asynchronous task that you want to keep running after returning a response to the visitor. Usually the Workers runtime will cancel any background tasks spawned from a particular FetchEvent once it detects that the response has been sent. event.waitUntil() tells the runtime to wait for another promise in addition to the visitor response before canceling any tasks. This probably doesn’t apply to your immediate needs. Further, event.waitUntil() doesn’t return anything, so treating its return value as anything other than undefined will lead to an exception.

Harris


Workers async method
CF worker to log all REST API activity in a non-blocking way to an external service - including response time
#4

Thanks @harris - this is Amit from Tallyfy.

To clarify further, is (1) await fetch(request) and (2) fetch(request).then(response => { if response.status === 404) ... } precisely functionally equivalent?

In the case of (1) does code carry on executing, or does it block at that point until the promise is returned? I require the code to pause until the promise if fulfilled, otherwise there’s no point checking for a 404 on an empty object.


#5

@harris please see a quick followup question here:


#6
const something = await func();
console.log(something);

is equivalent to

func().then(something => console.log(something)

This is not Cloudflare specific, async/await is part of modern JavaScript, intended to make async code easier to write.