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

181
Visualizações
How to wait for a variable to be populated by an api request before passing it to a webpage as an argument?

I'm new to JavaScript and cannot seem to make this work , the topic of quiz depends on the user input... when the user presses next , I get the topic (this also takes user to the main quiz page), then i have to fetch data from the api with the topic as a parameter... I have to process the result of the fetch operation.. Then I have to pass that info to to the main quiz page... but the variable that is supposed to be populated by the fetch request is still undefined when i pass is to the main quiz page

var Allquestions;
var sheetdb = require('sheetdb-node');

// create a config file
var config = {
  address: 'https://sheetdb.io/api/v1/9djmf8ydc7hwy',
};

//sheetdb
// Create new client
var client = sheetdb(config);


function downloadquestions(topic) {
  console.log(topic);
  client.read({ limit: 2, sheet: topic }).then(function(data) {
    console.log(data + " in client.read func")
    processQuestions(data);
    
  }, function(err){
    console.log(err);
  });
}

async function processQuestions(data) {
  console.log(data + "data in process");
  Allquestions  =  JSON.parse(data);
  console.log(Allquestions[0].Question  + " This is defined");

}

app.get("/", (req, res) => {
  res.render("pages/index", { title: "Home"});
});

// app.post("/" , urlencodedParser ,(req , res) => {
//   console.log(req.body.topic);  
// })

app.get("/questions", urlencodedParser , (req , res) => {
  downloadquestions(req.body.topic);
  console.log(Allquestions + " this is undefined");
  res.render("/pages/quizpage" , {Allquestions})

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

0

There are a few issues with your code, you have a broken promise chain, client.read( is a promise, and that promise is going nowhere. You either return it, or await it. To be able to await your will need to also mark your route (req, res) as async too.

Your code is a little mixed up, you have Allquestions as a global var, this isn't great for multi-user, as the last topic is going to override this each time.

Also try and avoid swallowing exceptions in utility functions, try and keep your exception handling at the top level, eg. in your case inside your req/res handler.

So with all this in mind, your refactored code could look something like ->

const sheetdb = require('sheetdb-node');

// create a config file
const config = {
  address: 'https://sheetdb.io/api/v1/9djmf8ydc7hwy',
};

//sheetdb
// Create new client
const client = sheetdb(config);

async function downloadquestions(topic) {
  const data = await client.read({ limit: 2, sheet: topic });
  return processQuestions(data);
}

function processQuestions(data) {
  return JSON.parse(data);
}

app.get("/", (req, res) => {
  res.render("pages/index", { title: "Home"});
});

app.get("/questions", urlencodedParser , async (req , res) => {
  try {
    const allQuestions = await downloadquestions(req.body.topic);
    res.render("/pages/quizpage" , {Allquestions});
  } catch (e) {
    console.error(e);
    res.end('There was an error'); 
  }
})
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