2

I am a beginner with express. In my index.js I have the following code :

app.get('/', (req, res) => {
  var gui = guiText("index", lang);
  //var gui =  [ 'Activities', 'Declensions', 'Conjugations' ];
  res.render("index", {gui: gui});
  console.log ("sent gui", gui)
  })

guiText("index", lang) is a async function that calls a sqlite db to get the localized text. When run this code, I can see that res.render is sent before guiText() has returned so my gui is empty. If I uncomment

//var gui =  [ 'Activities', 'Declensions', 'Conjugations' ];

and comment out

var gui = guiText("index", lang);

my html file correctly gets the information it needs to display. If I try

var gui = await guiText("index", lang);

I got the message as it is not possible. How I can work around this problem?

Edit : upon Heiko Theißen suggestion (this a very interesting post, but not very easy for a beginner), I tried to use a callback. my guiText function is now :

 guiText(page, lang, myCallback){

and ends with

 myCallback("index",{gui:result});

This function is called by :

app.get('/', (req, res) => { guiText("index", lang, app.res.render);

but I get the following error

TypeError: Cannot read properties of undefined (reading 'render')

How should I write the callback ?

  • 1
    Change `(req, res) => {` to `async (req, res) => {` – Patrick Roberts Jun 10 '22 at 17:12
  • Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Heiko Theißen Jun 10 '22 at 17:16
  • Thanks for your answer, but I still have the same problem. Console output still shows that the function doesn't wait guitText to return. sent gui Promise { } result [ 'Activities', 'Declensions', 'Conjugations' ] – Alain Bertrand Jun 10 '22 at 17:25
  • `app.get('/', (req, res) => {guiText("index", lang, res.render.bind(res))})` – Heiko Theißen Jun 10 '22 at 18:40

1 Answers1

3

Try this:

app.get('/', async (req, res) => {
  var gui = await guiText("index", lang);
  //var gui =  [ 'Activities', 'Declensions', 'Conjugations' ];
  res.render("index", {gui: gui});
  console.log ("sent gui", gui)
  })

You can see that all I did was add the async keyword before (req, res) and await before guiText("index", lang); await wasn't working when you tried it because you forgot to make the entire app.get callback an async function.

christian_js
  • 298
  • 3
  • 11