How to pass model result to view in node js

I m new to node.js, try to making some small app.All is good but i m not able to pass model data outside the function:

Working Code is:

usermodel = require('../models/usermodel.js');
exports.index = function(req, res) {
var stuff_i_want = '';
 usermodel.userlist(req, function(result)
 {
    //stuff_i_want = result;
    res.render('index.ejs', {
                title: "Welcome to Socka | View Players",
                players:result
            });
    //rest of your code goes in here
 });
   console.log(stuff_i_want);


};

but i want some thing like:

usermodel = require('../models/usermodel.js');
exports.index = function(req, res) {
var stuff_i_want = '';
 usermodel.userlist(req, function(result)
 {
    stuff_i_want = result;

    //rest of your code goes in here
 });
   console.log(stuff_i_want);
    res.render('index.ejs', {
                title: "SA",
                players:result
            });


};

Upvotes: 1

Views: 576

Answers (1)

Jasper Bernales
Jasper Bernales

Reputation: 1681

You are calling an asynchronous function userlist that's why you need it inside the callback. You can use Promise libraries like bluebirdjs and refactor your usermodel implementation to standard nodejs function arguments (err, result). In this case you can refactor it like the this below

const usermodel  = require('../models/usermodel.js');
exports.index = async function(req, res) {
 const players = await new Promise((resolve, reject) => {
   usermodel.userlist(req, function(result){
     resolve(result)
   });
 })
 res.render('index.ejs', {
   title: "SA",
   players
 });


};

Upvotes: 1

Related Questions