Search code examples
javascriptnode.jsexpressserver

How to create a loading animation using "response.send()", then change it to the result of a promise after it is resolved?


I am trying to create a loading animation using "response.send()" (could be response.sendFile() too), and then to change the content of "response.send()" with the results of a promise after it is resolved.

app.get("/image/:id", async (request, response) => {
    response.send("loading");

    serveImage(request.params.id).then((result) => {
      response.send(result);
    });
}

I keep getting the following error.

UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

How can I circumvent this?


Solution

  • You can't send more that one response with Express' response.send(). You can call response.write() more than once, but most clients will be waiting for the end of the response before communicating the result back to your code anyway, so unless you have a very special type of client, that probably won't help either.

    What you should probably do is to have the client itself put up the loading... when it makes the request and then when it gets the final result, it can take that down and display the result. Make that part of the presentation be controlled by the client itself rather than the server.