如何使用 Cloudflare Worker 发出异步请求(非阻塞)

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

我正在编写一个 Cloudflare Worker,它需要在我的原始请求完成后对分析服务执行 ping 操作。我不希望它阻止原始请求,因为我不希望分析系统的延迟或故障减慢或中断请求。如何创建在原始请求完成后开始和结束的请求?

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
}

您需要使用Event.waitUntil()来延长请求的持续时间。默认情况下,所有异步任务在发送最终响应后立即取消,但您可以使用 waitUntil() 来延长请求处理生命周期以适应异步任务。 waitUntil() 的输入必须是任务完成时解析的 Promise。

所以,而不是:

await promise

做:

event.waitUntil(promise)

Here's the full working script in the Playground.