简体   繁体   English

当 promise 用于动态部分时,如何将 static 和动态数据包含到快速渲染 function 中?

[英]How to include static and dynamic data into an express render function when a promise is used for the dynamic part?

I'm working on a web application with Node and Express and want to display content from different JSON files.我正在使用 Node 和 Express 开发 web 应用程序,并希望显示来自不同 JSON 文件的内容。 Some contain static content like headings and column labels for tables.有些包含 static 内容,例如表格的标题和列标签。 Some contain user data that can change dynamically.有些包含可以动态更改的用户数据。 First, I made two different functions to read the JSON files:首先,我做了两个不同的函数来读取 JSON 文件:

const readStaticData = filePath => {
 fs.readFile(filePath, 'utf-8', (err, staticData) => {
    if (err) throw err;
    JSON.parse(staticData);
 }); 
};

and this for dynamic data:这对于动态数据:

const readData = filePath => new Promise((resolve, reject) => {
  fs.readFile(filePath, (err, fileData) => {
      if (err) {
          reject(err);
          return;
      }
      try {
          const object = JSON.parse(fileData);
          resolve(object);
      } catch(err) {
          reject(err);
      }
  });
});

And this is how my router.get() function looks so far:这就是我的 router.get() function 到目前为止的样子:

router.get('/', (req, res) => {
  Promise.all([
    readData('./JSON/dynamicData1.json'),
    readData('./JSON/dynamicData2.json')
  ])
  .then((data) => {
    res.render('home',
      {
        dynamicData1: data[0],
        dynamicData2: data[1]
      }
    );
  })
  .catch((err) => {
    console.log(err);
    res.status(500).end();
  });
});

So I have my render function inside the Promise and I'm stuck how I can include the static content as well.所以我在 Promise 中有我的渲染 function 并且我不知道如何包含 static 内容。 Where can I put my readStaticData('./JSON/staticData1.json'); readStaticData('./JSON/staticData2.json');我可以把readStaticData('./JSON/staticData1.json'); readStaticData('./JSON/staticData2.json');放在哪里? readStaticData('./JSON/staticData1.json'); readStaticData('./JSON/staticData2.json'); functions to render?渲染功能? They don't depend directly on the dynamic content, eg a headline should always be there whether there is user data or not.它们不直接依赖于动态内容,例如,无论是否有用户数据,标题都应该始终存在。

Hopefully I'm not missing important information, this is my first question here.希望我没有遗漏重要信息,这是我的第一个问题。 And I'm also new to programming.而且我也是编程新手。 If someone could help thanks a lot in advance!如果有人可以帮助,请提前致谢!

I would do it something like this.我会这样做。 You can just require a JSON file and have it ready to go as it is static.您可以只需要一个 JSON 文件并将其准备好到 go,因为它是 static。

const staticData = require('./path/to/staticData.json') 

// const readStaticData = filePath => {
//     fs.readFile(filePath, 'utf-8', (err, staticData) => {
//         if (err) throw err;
//         JSON.parse(staticData);
//     });
// };

const readData = filePath => new Promise((resolve, reject) => {
    fs.readFile(filePath, (err, fileData) => {
        if (err) {
            reject(err);
            return;
        }
        try {
            const object = JSON.parse(fileData);
            resolve(object);
        } catch(err) {
            reject(err);
        }
    });
});

router.get('/', (req, res) => {
    Promise.all([
        readData('./JSON/dynamicData1.json'),
        readData('./JSON/dynamicData2.json')
    ])
        .then((data) => {
            res.render('home',
                {
                    dynamicData1: data[0],
                    dynamicData2: data[1],
                    staticData
                }
            );
        })
        .catch((err) => {
            console.log(err);
            res.status(500).end();
        });
});

fs.readFile is always asynchronous, so you can use readData in both cases. fs.readFile始终是异步的,因此您可以在这两种情况下使用 readData。

There's also a synchronous version of it: fs.readFileSync .它还有一个同步版本: fs.readFileSync

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM