My node js program is giving me a “TypeError: Cannot read property 'then' of undefined”, when reading a json file

荒凉一梦 提交于 2021-02-11 13:41:31

问题


I'm trying to read frpm a json file folder withing my program and i want to use a GET list endpoint to read through browser or postman, but i'm getting the above TypeError. Here is my code:

model.js:

const fs = require('fs');

  function loadTeams() {
    return new Promise((resolve, reject) => {
      fs.readFile('./json/prov-nodes.json', (err, data) => {
          if (err) reject(err);
          const teams = JSON.parse(data);
          console.log(teams);
          resolve(teams);
      });
    });
}

app.use(bodyParser.json());

app.get('/list', (req, res) => {
    let teams = [];
    loadTeams()
      .then(function(data){   
        teams = JSON.stringify(data); 
        console.log(teams);  
        **res.send(teams);** //intended to send to browser/postman response
        console.log('try...part ..read call');

      })
      .catch(error => console.log(error))
      res.send("My root page");
      console.log(teams);
     
});

回答1:


The loadTeams function does not return a promise, and therefore you cannot call .then().

You can wrap the function in a promise like this:

function loadTeams() {
    return new Promise(function(resolve, reject) {
        fs.readFile('./json/prov-nodes.json', (err, data) => {
            if (err) reject(err);
            try {
                const teams = JSON.parse(data);
                return resolve(teams);
            } catch(e) {
                reject(e);
            }
        });
    });
}



回答2:


In order to use loadTeams as an async function you should turn it into a function that returns Promise with a callback results:

function loadTeams() {
  return new Promise((resolve, reject) => {
    fs.readFile('./json/prov-nodes.json', (err, data) => {
        if (err) reject(err);
        const teams = JSON.parse(data);
        console.log(teams);
        resolve(teams);
    });
  });
}


来源:https://stackoverflow.com/questions/65423753/my-node-js-program-is-giving-me-a-typeerror-cannot-read-property-then-of-und

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!