Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
85 views
in Technique[技术] by (71.8m points)

node.js - In Node js, why is my controller.js not showing the data after invoking a model.js function

I'm new to Nodejs and i've fetched a json file using require and fs, and using MVC , i have a model.js that has the function that reads the json file, but when the controller invokes the model function, the data is not shown (console.log(data) in the controller, but console.logged in the model.js. Here is my code:

controller.js

exports.renderHomePage = (req, res) => {
    
    apiServerModel.loadTeams()
        .then(function (data) {
            console.log(data);
            console.log("This is inside controller")
            res.render("index", { // output as string
                teamsList: `${JSON.stringify(data, null, 2)}`    // A property called teamList to be displayed on the browser
                //teamsList: teamView.TeamsView(`${JSON.stringify(data, null, 2)}`)
        })
    })
    .catch(error => console.log(error))
}

model.js

'use strict';

const fs = require('fs');

class TeamsModel {

    static async loadTeams() {  
      try {
           await fs.readFile('./json/prov-nodes.json', (err, rawData) => {
          if (err) throw err;
          let teams = JSON.parse(rawData);
          return teams;
          //console.log(teams);
        });
      } catch (error) {
        console.log(error)
      }
      console.log('This is after the read call');
    }

  }

  exports.TeamsModel = TeamsModel; 
question from:https://stackoverflow.com/questions/65649339/in-node-js-why-is-my-controller-js-not-showing-the-data-after-invoking-a-model

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

first of all you should read about Callbacks VS Promises VS Async/Await in node.js.

when you use async/await, don't have a callback so:

use fs/promises instead of fs, because you used await for fs in your loadTeams function.

'use strict';

const fs = require('fs/promises');

class TeamsModel {

    static async loadTeams() {  
      console.log("hi")
      try {
           let rawData = await fs.readFile('./json/prov-nodes.json')
          let teams = JSON.parse(rawData);
          return teams;

      } catch (error) {
        console.log(error)
      }
      console.log('This is after the read call');
    }

  }

  module.exports = TeamsModel; 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...