gpt4 book ai didi

javascript - 将上下文添加到 Mongoose 回调

转载 作者:行者123 更新时间:2023-11-30 09:01:32 25 4
gpt4 key购买 nike

将上下文添加到模型查询中使用的回调的正确方法是什么?例如……

function doSomething(param) {
var magic = function(context, err, results) {
if(err) { console.log('fail'); }
else {
// do the magic with context and results
}
}

for( var i=0; i < 5; i++ ) {
var myObject = {'secret' : i};
MyModel.find({number:param[i]}, magic(myObject, err, results));
}
}

我想遍历每个查询的结果并拥有 myObject 的上下文。上述解决方案不起作用。 “错误”和“结果”未定义。

我通常使用匿名函数执行此操作,但我不能依赖 for 循环内的上下文。

最佳答案

errresults 是未定义的,因为您正在将名为 errresults 的变量传递给 你从未定义过的魔法

MyModel.find 不能对 magic 的结果做任何事情,因为你没有从它返回任何东西,你应该返回一个接受 的函数>错误结果

function doSomething(param) {
var magic = function(context) {
// return a function here
return function(err, results) {
if(err) { console.log('fail'); }
else {
// do the magic with context and results
}
};
}

for( var i=0; i < 5; i++ ) {
var myObject = {'secret' : i};
// do not pass err or results to magic
// they are not defined anywhere in this scope
MyModel.find({number:param[i]}, magic(myObject));
}
}

关于javascript - 将上下文添加到 Mongoose 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8858246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com