Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how to synchronously send a response and then continue? #3557

Closed
huseeiin opened this issue Feb 14, 2025 · 1 comment
Closed

how to synchronously send a response and then continue? #3557

huseeiin opened this issue Feb 14, 2025 · 1 comment

Comments

@huseeiin
Copy link

i can't do this:

addEventListener("fetch", async (e) => {
  e.respondWith(Response.json({}));

  await new Promise((r) => setTimeout(r, 5000));
  console.log("timeout");
});

meanwhile i can do this in node:

import { createServer } from "http";

createServer(async (req, res) => {
  res.end("Hello");

  await new Promise((r) => setTimeout(r, 5000));
  console.log("timeout");
});
@kentonv
Copy link
Member

kentonv commented Feb 14, 2025

You need to use waitUntil() to tell the runtime about tasks that you want to keep running after the response is returned, otherwise the runtime automatically cancels everything when the event is "done".

https://developers.cloudflare.com/workers/runtime-apis/context/#waituntil

export default {
  async fetch(req, env, ctx) {
    ctx.waitUntil(logLater());
    return Respnose.json({});
  }
}

async function logLater() {
  await scheduler.wait(5000);
  console.log("timeout");
}

@kentonv kentonv closed this as completed Feb 14, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants