Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
}
like image 862
Zack Bloom Avatar asked Mar 14 '18 20:03

Zack Bloom


1 Answers

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.

like image 112
Kenton Varda Avatar answered Nov 14 '22 00:11

Kenton Varda