How can I make an asynchronous request (non-blocking) using a Cloudflare Worker
Asked Answered
G

1

6

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
}
Gnathic answered 14/3, 2018 at 20:21 Comment(0)
R
5

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.

Ratiocinate answered 14/3, 2018 at 20:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.