1

I would like to dynamically display the variable that I get using this Async function:

    async function makeGetRequest() {
      res = await axios.get(url);
      xml2js.parseString(res.data, function (err, file) {
      return file.item[0].title; });
}

makeGetRequest().then(console.log);


**OUTPUT: TITLE:[object Promise]**

Instead of logging the value like in the above snippet, I'd like to pass the value to Express renderer to dynamically render the value on a page:

app.get('/dynamic', function(req, res){
    res.render('dynamic', {
       title: title_value_here;
    });
 });

Could someone show how this can be achieved?

I tried storing the Async output in variable to then pass it to renderer but I got this:

let out= await makeGetRequest();
console.log(author);
SyntaxError: await is only valid in async functions and the top level bodies of modules
beginner
  • 89
  • 1
  • 4

2 Answers2

1

Currently, async/await is not supported for the pug language. This means you will have to await the result and pass to the template as suggested by this answer: https://stackoverflow.com/a/68302690/10343551

Here is an issue that was marked closed (a while ago) regarding adding async to the pug language. One of the contributors speaks to pugs design being synchrounous: https://github.com/pugjs/pug/issues/2206#issuecomment-169881732

From what I can tell (as of Dec 2021) async hasn't been added. This means you cannot await inside of a template and have to do it prior to rendering the template and pass it in.

0

You can just put it in app.get.

app.get('/dynamic', async function(req, res){
  const out = await makeGetRequest();
  res.render('dynamic', {
    title: <use out here>;
  });
});
Aritra Chakraborty
  • 12,123
  • 3
  • 26
  • 35
  • Thanks, but for some reason I actually cant save the value of the output variable: `makeGetRequest().then(console.log);` Gives `'TITLE1'`, but: `let author= await makeGetRequest(); console.log(author); SyntaxError: await is only valid in async functions and the top level bodies of modules` EDIT: using `makeGetRequest().then(out => { console.log(out)});` gives `undefined` – beginner Jul 08 '21 at 13:45
  • you didn't do what I have showed in answer. so what do you mean this comment? – Aritra Chakraborty Jul 08 '21 at 15:56