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

编程入门 行业动态 更新时间:2024-10-24 04:48:57
本文介绍了如何使用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("example") .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("example") .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发出异步请求(非阻塞)

本文发布于:2023-11-25 09:02:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1629147.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   Cloudflare   Worker

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!