Skip to content Skip to sidebar Skip to footer

Update Message In View After View Has Been Rendered In Express ( Once Asynchronous Code Is Executed )

I am building a small express app that basically just reads the files from a directory renames them and then zips the files , now the reading and renaming part of the files is done

Solution 1:

You are correct about not being able to send multiple res.render. In standard HTTP, a client expects to receive a fixed content length and you won't be able to change it later while sending it.

Usually, when you want to achieve something like this, have your client send a second request, which blocks until the server really is done with its async actions. You could use a websocket connection or something very sophisticated, but here is a small example leveraging express' ability to dynamically use routes:

const express = require("express");
const app = express();

let jobs = {};

app.get("/jobs/:number.js", (req, res) => {
  const jobNr = req.params.number;
  const job = jobs[jobNr];
  if (!job) {
    console.log("no job found!");
    return res.sendStatus(404);
  }

  job
    .then(result => res.send(`document.getElementById("result-${jobNr}").innerHTML = "job ${jobNr} is done with ${result}";`))
    .catch(err => res.sendStatus(500))
    .then(() => {
      // finally clean up, as some client requested this resource
      jobs[jobNr] = null;
    });
});

app.get("/", (req, res) => {

  // set up a job with whatever is necessary to doconst jobNr1 = Math.floor(Math.random() * 10000000);
  const job = newPromise(resolve =>setTimeout(() =>resolve("a result!"), Math.random() * 5000 + 2000));
  jobs[jobNr1] = job;

  // set up a second job with whatever is necessary to doconst jobNr2 = Math.floor(Math.random() * 10000000);
  const job2 = newPromise(resolve =>setTimeout(() =>resolve("another result!"), Math.random() * 5000 + 2000));
  jobs[jobNr2] = job2;

  res.send(`<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>test</title>
</head>
<body>
  <div id="result-${jobNr1}">job ${jobNr1} running...</div>
  <div id="result-${jobNr2}">job ${jobNr2} running...</div>
  <script async src="/jobs/${jobNr1}.js"></script>
  <script async src="/jobs/${jobNr2}.js"></script>
</body>
</html>
`);
});

app.listen(8080);

Post a Comment for "Update Message In View After View Has Been Rendered In Express ( Once Asynchronous Code Is Executed )"