Gre*_*reg 1 javascript mongoose node.js
将上下文添加到Model查询中使用的回调的正确方法是什么?例如...
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));
}
}
Run Code Online (Sandbox Code Playgroud)
我想遍历每个查询的结果并拥有myObject的上下文.上述解决方案不起作用."错误"和"结果"未定义.
我通常使用匿名函数执行此操作,但我不能依赖for循环中的上下文.
err并且results是不确定的,因为你arer传递一个变量叫err和results给magic你从未定义.
MyModel.findmagic因为你没有从中返回任何内容而无法对结果做任何事情,你应该返回一个带err和的函数result.
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));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1094 次 |
| 最近记录: |