【发布时间】:2020-08-10 09:28:18
【问题描述】:
提前感谢您阅读本文的任何人。我非常感谢任何和所有的帮助。
所以这是我的第一个应用程序个人应用程序。我在 mongodb.com 上的 Atlas 中设置了一个数据库,我可以毫无问题地写入它。但是当我的应用程序尝试从我的数据库中提取时,我可以让它打印到控制台。但我可以将数据分配给任何变量,以便在我的应用程序的其他任何地方使用。
这是我可以打印到控制台的代码。但不确定我缺少什么设置或包,因此我可以将其存储为局部变量。我正在使用回调函数来返回 api 调用,并且控制台打印输出工作正常。只是不知道下一步该做什么
function getTerms() {
let allTerms = []
termAdd.find({}, '_id', (err, term) => {
term.map((term) => {
allTerms.push(term)
// if I understand Push() correctly this should store my output to allTerms.
});
//this works to print out to console in JSON.
console.log(allTerms, 'getTerms')
return allTerms;
});
};
if (res.statusCode === 200) {
//callback function to return the console from the function
getTerms()
// when i do a let foo = getTerms() it will return undefined
//so I am really dont understand how to assign the return from
//the function to a variable.
//How do I assign this console output to variable to use for output
console.log('200 statusCode')
};
//Random Number Generator
let ranNum = Math.floor((Math.random() * 10) + 1);
console.log('random number = ',ranNum);
res.render('fs', {
flashCard : 'Test Card',
items: ranNum
});
});
如果能帮助我链接到这个项目,我在 GitHub 上有完整的代码。
无论如何我都应该使用延迟吗?有人给了我一个建议。但我不明白我在读什么。
【问题讨论】:
-
我正在尝试了解您要存储的内容;是字符串'200 statusCode'吗?对不起
-
所以我试图存储 getTerms 函数的返回值。但是当我分配“let foo = getTerms()”时,它会返回并在控制台中统一。那么数据在哪里
-
我相信在做任何事情之前,你应该分离你的功能;
getTerms()发生的事情太多了。如果我没记错的话,你是不是又在里面给getTerms()打电话了? -
你能分享剩下的代码吗?
-
哦不不不!删除那个。永远不要分享那个链接;它包含您的数据库的 URI 和您的密码。事实上,最好不要共享 .env 中的任何内容,也不要将 .env 文件推送到 Github
标签: javascript node.js mongoose