Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何将模型结果传递到节点js中的视图_Node.js_Express - Fatal编程技术网

Node.js 如何将模型结果传递到节点js中的视图

Node.js 如何将模型结果传递到节点js中的视图,node.js,express,Node.js,Express,我是node.js新手,尝试制作一些小应用程序。一切都很好,但我无法将模型数据传递到函数之外: 工作守则如下: usermodel = require('../models/usermodel.js'); exports.index = function(req, res) { var stuff_i_want = ''; usermodel.userlist(req, function(result) { //stuff_i_want = result; res.rende

我是node.js新手,尝试制作一些小应用程序。一切都很好,但我无法将模型数据传递到函数之外:

工作守则如下:

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);


};
但我想要一些东西,比如:

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
            });


};

您正在调用一个异步函数
userlist
,这就是为什么您需要在回调中使用它。您可以使用Promise库,例如,将usermodel实现重构为标准的nodejs函数参数
(err,result)
。在这种情况下,您可以像下面这样重构它

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
 });


};

小建议——尝试将代码的格式设置得更干净、更一致。缩进使用相同数量的空格,代码段之间使用1个空格,例如
usermodel=require(…)
。如果你发布凌乱的代码,人们不会认为你太在意一个深思熟虑的答案。除非你等待,否则不可能执行某个
async
(通过回调)并获得该.userlist的结果。将所有内容都放在回调函数(result){中的问题是什么?问题是,假设我有多个数据要从不同的模型传递到视图中,在这种情况下,您能建议哪种解决方案是可行的。@iwaduarte