Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

158
Visualizações
How can I get the result from function to json value?

I'm so new to node.js I'm trying to make an interval value in node.js And I can invoke a function when I reach the exact URL, however, I do not know how to pass the console.log value to JSON value.

this is my code:

// Import packages
const express = require("express");
// App
const app = express();
   

const port = 8000;

app.get("/", (req, res) => {
  function doSomething() {
    console.log(Math.round(Math.random() * (3000 - 500)) + 500);
  }

  const loop = () => {
    setTimeout(() => {
      doSomething();
      loop();
    }, 1000);
  };
  loop();

  res.json({ random: doSomething() });
});
// Starting server
app.listen(port, () => console.log(`listening on port ${port}!`));

I'd like to pass the random number in doSomething function to res.json` inside.

So, this is what I tried :

// Import packages
const express = require("express");
// App
const app = express();
   

const port = 8000;

let number;

app.get("/", (req, res) => {
  function doSomething() {
    number = Math.round(Math.random() * (3000 - 500)) + 500;
    return number;
  }

  const loop = () => {
    setTimeout(() => {
      doSomething();
      loop();
    }, 1000);
  };
  loop();

  res.json({ random: doSomething() });
});
// Starting server
app.listen(port, () => console.log(`listening on port ${port}!`));
However, the above code is working only I refresh the page, I'd like to change it every second without refresh.

Thank you in advance

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I think it would be better to invoke your function from the client and using setInterval instead of setTimeout otherwise it only will run it once.

Keep your server code like this:

// Import packages
const express = require("express");
// App
const app = express();
   

const port = 8000;

let number;

app.get("/", (req, res) => {
  function doSomething() {
    number = Math.round(Math.random() * (3000 - 500)) + 500;
    return number;
  }

  res.json({ random: doSomething() });
});
// Starting server
app.listen(port, () => console.log(`listening on port ${port}!`));

Then, in a js loaded from the client (browser), you could do something like this:

setInterval(() => {
  fetch("http://localhost:8000/")
    .then(res => res.json())
    .then(res => console.log(res))
    .catch(err => console.log("err", err))

}, 1000)

That said, using setInterval may not be the best thing. I would recommend you to create a HTML <button> or an <a> and set up and event listener to handle the click event. Then, when the user clicks the button, you could invoke a function to execute the fetch operation.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda