-1

i am trying to create a function for rendering views in NodeJS that will be called using await later on.

const getTemplate = async (template, context) => {
  app.render(template, { data: context }, (error, html) => {
    return html;
  });
}

const data = require('./data.json');

app.get('/pdf', async (req, res) => {
  const html = await getTemplate('invoice', data);
  res.send(html);
});

Right now it gives me an empty response and that's probably because it exits the getTemplate function before the render callback fires, but i don't know how to modify it in an elegant way.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Pacuraru Daniel
  • 1,207
  • 9
  • 30
  • 56

1 Answers1

3

You need to return a promise from getTemplate. Since you want to wait for the app.render to finish, I hope the following code does what you intend to do :)

// `async` is not really necessary as you are not using `await`, but you may provide it, if you want
const getTemplate = /* async */ (template, context) => {
  return new Promise((resolve, reject) => {
    app.render(template, { data: context }, (error, html) => {
      if (error) return reject(error);
      return resolve(html);
    });
  });
}

const data = require('./data.json');

app.get('/pdf', async (req, res) => {
  const html = await getTemplate('invoice', data);
  res.send(html);
});
Narigo
  • 2,979
  • 3
  • 20
  • 31
  • 1
    Not that it's wrong but I tend to prefer `if (error) reject(error); else resolve(html);` to emphasize that the callback doesn't really use a `return` value, since it's ignored. – Patrick Roberts Jan 02 '19 at 15:56