javascriptnode.jsexpressasync-awaitnode-promisify

Promisify Express response.render method


I need to create a render method to build html blocks into a string. It seems to work but I used the notorious "new Promise" and I wanted to know if what I've done is either correct or not:

async render(req, res) {
  const locals = await this.execute(req); // DB operation, retrieve context
  return new Promise((resolve, reject) => {
    try {
      return res.render('my-view', { ...locals, layout: null }, (err, html) => { 
        if (err) {
          return reject(err);
        }
        return resolve(html);
      });
    } catch (err) {
      return reject(err);
    }
  });
}

Thank you!


Solution

  • The new Promise constructor implicitly catches (synchronous) exceptions from the executor callback, so that try/catch is not needed. Also, the return value is ignored. You'd write just

    async render(req, res) {
      const locals = await this.execute(req); // DB operation, retrieve context
      return new Promise((resolve, reject) => {
        res.render('my-view', { ...locals, layout: null }, (err, html) => { 
          if (err) reject(err);
          else resolve(html);
        });
      });
    }