I'm writing a Cloudflare Worker that needs to ping an analytics service after my original request has completed. I don't want it to block the original request, as I don't want latency or a failure of the analytics system to slow down or break requests. How can I create a request which starts and ends after the original request completes?
addEventListener('fetch', event => {
event.respondWith(handle(event))
})
async function handle(event) {
const response = await fetch(event.request)
// Send async analytics request.
let promise = fetch("https://example.com")
.then(response => {
console.log("analytics sent!")
})
// If I uncomment this, only then do I see the
// "analytics sent!" log message. But I don't
// want to wait for it!
// await promise;
return response
}
You need to use Event.waitUntil()
to extend the duration of the request. By default, all asynchronous tasks are canceled as soon as the final response is sent, but you can use waitUntil()
to extend the request processing lifetime to accommodate asynchronous tasks. The input to waitUntil()
must be a Promise which resolves when the task is done.
So, instead of:
await promise
do:
event.waitUntil(promise)
Here's the full working script in the Playground.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With