How to send an early response and continue executing #3163
-
I am migrating a Google Cloud function to a Bun/Hono backend. My function currently allows me an early response and continue to proceed with the rest of the code. Google Cloud function: export const create_backup = v2.https.onRequest(
async (request, response) => {
const { id: backupId } = ...
// Early response to the client, as Sveltekit expects a response within 15 seconds. The backup will continue in the background, and we'll get notified
response.status(HttpStatusCode.Accepted).json({
status: 'In progress',
data: { backupId },
});
// Continue to work
...
); In Hono, I tried to simply use c.json(
{
status: 'In progress',
data: { backupId },
},
HttpStatusCode.Accepted
);
// above never sends anything back to the client
// ... continue |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
Hi @gregoryforel. If you use Cloudflare Workers, can use c.executionCtx.waitUntil((async () => {
// This code is executed after the server has respond
})())
return c.json(
// ^ You have to add `return`
{
status: 'In progress',
data: { backupId },
},
HttpStatusCode.Accepted
); If you don't, probably you can use like that: ;(async () => {
// Describe the subsequent processing in this code
})()
return c.json(
// ^ You have to add `return`
{
status: 'In progress',
data: { backupId },
},
HttpStatusCode.Accepted
); |
Beta Was this translation helpful? Give feedback.
-
So, I'm not using Cloudflare Workers, and unfortunately, the other async solution does not work. I solved the issue using |
Beta Was this translation helpful? Give feedback.
-
@mikkelsvartveit sorry, I hadn't seen your question. return streamSSE(c, async (stream) => {
// Send early response to the client (Sveltekit needs to receive a response within 15 seconds)
await stream.write(
JSON.stringify({
status: HttpStatusCode.Accepted,
})
);
// Close the stream to send the response immediately
await stream.close();
// ... rest of the processing continues ...
}); |
Beta Was this translation helpful? Give feedback.
@mikkelsvartveit sorry, I hadn't seen your question.