如何从嵌套查询中返回值?我想将结果保存到全局变量。有人可以帮助我吗?
let result = null;
const returnMeal = () => {
Dinner1300.count().exec(function (err, count) {
const random = Math.floor(Math.random() * count)
Dinner1300.findOne().skip(random).exec(
function (err, result) {
console.log(result)
})
})
答案 0 :(得分:1)
您可以更改代码以使用Promise,或者只是传递一个回调以返回returnMeal并在那里处理响应
const returnMeal = clb => {
Dinner1300.count().exec(function (err, count) {
const random = Math.floor(Math.random() * count)
Dinner1300.findOne().skip(random).exec(
function (err, result) {
clb(result)
})
})
}
returnMeal(result => {
console.log(result);
// move all your logic to handle the result here
})
答案 1 :(得分:0)
只需将结果分配给全局声明的变量。
let result = null;
const returnMeal = () => {
Dinner1300.count().exec(function (err, count) {
const random = Math.floor(Math.random() * count)
Dinner1300.findOne().skip(random).exec(
function (err, result) {
global.result = result;
console.log(global.result)
})
})
答案 2 :(得分:0)
使用module.exports
let result = null;
const returnMeal = () => {
Dinner1300.count().exec(function (err, count) {
const random = Math.floor(Math.random() * count)
Dinner1300.findOne().skip(random).exec(
function (err, res) {
result = res;
console.log(result);
});
});
module.exports = result;
答案 3 :(得分:0)
在函数中传递结果并在全局范围内设置值。
var globalScope = null;
Dinner1300.count().exec(function (err, count) {
const random = Math.floor(Math.random() * count)
Dinner1300.findOne().skip(random).exec(
function (err, result) {
setValue(result)
})
})
function setValue(result) {
globalScope = result;
}