如何使用Cloudflare Worker发出异步请求(非阻塞) [英] How can I make an asynchronous request (non-blocking) using a Cloudflare Worker

查看:961
本文介绍了如何使用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)

这是游乐场中的完整工作脚本.

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.

这篇关于如何使用Cloudflare Worker发出异步请求(非阻塞)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆