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

。_饼干妹妹 提交于 2019-12-10 14:19:36

问题


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
}

回答1:


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.



来源:https://stackoverflow.com/questions/49287008/how-can-i-make-an-asynchronous-request-non-blocking-using-a-cloudflare-worker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!