Skip to content
Edge Functions

后台任务

Run background tasks in an Edge Function outside of the request handler.

Edge Function 实例可以在请求处理程序之外处理后台任务。后台任务对于像上传文件到存储、更新数据库或向日志服务发送事件这样的异步操作非常有用。你可以立即响应请求,让任务在后台继续运行。

🌐 Edge Function instances can process background tasks outside of the request handler. Background tasks are useful for asynchronous operations like uploading a file to Storage, updating a database, or sending events to a logging service. You can respond to the request immediately and leave the task running in the background.

这让你可以:

🌐 This allows you to:

  • 在处理的同时回应用户
  • 处理异步操作时不阻塞响应

概览 #

🌐 Overview

你可以使用 EdgeRuntime.waitUntil(promise) 来显式标记后台任务。Function 实例会继续运行,直到提供给 waitUntil 的 promise 完成。

🌐 You can use EdgeRuntime.waitUntil(promise) to explicitly mark background tasks. The Function instance continues to run until the promise provided to waitUntil completes.

1
import { withSupabase } from 'npm:@supabase/server@^1'
2
3
// Mark the asyncLongRunningTask's returned promise as a background task.
4
// ⚠️ We are NOT using `await` because we don't want it to block!
5
EdgeRuntime.waitUntil(asyncLongRunningTask())
6
7
export default {
8
fetch: withSupabase({ auth: 'user' }, async (req, ctx) => {
9
return Response.json({ ok: true })
10
}),
11
}

你也可以在请求处理器中调用 EdgeRuntime.waitUntil。这不会阻塞请求。

🌐 You can call EdgeRuntime.waitUntil in the request handler too. This will not block the request.

1
import { withSupabase } from 'npm:@supabase/server@^1'
2
3
export default {
4
fetch: withSupabase({ auth: 'user' }, async (req, ctx) => {
5
// Won't block the request, runs in background.
6
EdgeRuntime.waitUntil(asyncLongRunningTask())
7
8
return Response.json({ ok: true })
9
}),
10
}

你可以监听 beforeunload 事件处理器,以便在函数即将关闭时收到通知。

🌐 You can listen to the beforeunload event handler to be notified when the Function is about to be shut down.

1
import { withSupabase } from 'npm:@supabase/server@^1'
2
3
EdgeRuntime.waitUntil(asyncLongRunningTask())
4
5
// Use beforeunload event handler to be notified when function is about to shutdown
6
addEventListener('beforeunload', (ev) => {
7
console.log('Function will be shutdown due to', ev.detail?.reason)
8
// Save state or log the current progress
9
})
10
11
export default {
12
fetch: withSupabase({ auth: 'user' }, async (req, ctx) => {
13
return Response.json({ ok: true })
14
}),
15
}

处理错误 #

🌐 Handling errors

我们建议在你的后台任务函数中使用 try/catch 块来处理错误。

🌐 We recommend using try/catch blocks within your background task function to handle errors.

你也可以给 unhandledrejection 添加一个事件监听器来处理没有拒绝处理程序的任何 promise。

🌐 You can also add an event listener to unhandledrejection to handle any promises without a rejection handler.

1
addEventListener('unhandledrejection', (ev) => {
2
console.log('unhandledrejection', ev.reason)
3
ev.preventDefault()
4
})

在本地测试后台任务 #

🌐 Testing background tasks locally

当使用 Supabase CLI 本地测试 Edge Functions 时,请求完成后实例会自动终止。这会导致后台任务无法执行完毕。

🌐 When testing Edge Functions locally with Supabase CLI, the instances are terminated automatically after a request is completed. This will prevent background tasks from running to completion.

为了防止这种情况,你可以用以下设置更新 supabase/config.toml:

🌐 To prevent that, you can update the supabase/config.toml with the following settings:

1
[edge_runtime]
2
policy = "per_worker"