我有以下循环:
params = ['Thing', 'AnotherThing', 'AnotherThingAgain'];
for (i in params){
MyModel.find(....).exec(function(err, data){
// do some stuff here
});
}
所以,当我的请求被执行时,我想使用params[i]
在回调函数中。问题是请求似乎是异步执行的,所以 params[i]
始终采用数组的最后一个值('AnotherThingAgain'
此处)。
如何将额外参数传递给该回调函数,以便在函数中使用它?
最佳答案
最简单的方法是使用闭包:
const params = ['Thing', 'AnotherThing', 'AnotherThingAgain'];
params.forEach((param, i) => {
MyModel.find(....)
.exec((err, data) => {
// do some stuff here with param or i
});
});
promise 示例:
// Some function to run on param
function searchParam(param) {
return MyModel.find({
param: {$eq: param},
})
.then((result) => {
// For eaxmple combine result with param...
return {
peram,
result,
};
});
}
const params = ['Thing', 'AnotherThing', 'AnotherThingAgain'];
Promise.all(params.map(searchParam))
.then((items) => {
// items is array of param, result pairs
items.forEach(({param, result}) => {
console.log(param, '=>', result);
});
});
关于javascript - Mongoose 如何在exec回调函数中传递额外参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37883586/