javascript - Mongoose 如何在exec回调函数中传递额外参数

标签 javascript node.js mongoose callback

我有以下循环:

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/

相关文章:

node.js - NodeJS 未定义的 var 出现错误

node.js - 如何从 Mongoose 对象内嵌套的数组中提取数组元素?

mongodb - Mongoose/mongoDB 删除唯一索引约束

javascript - reactJS props 和 refs 有什么区别?

javascript - Angular 中唯一的过滤选择列表仅返回数据集中的单个项目

javascript - 分析 NodeJS 高 CPU 使用率(表示 ___inc_remove_counter )

javascript - onblur 不起作用,但 onchange 起作用吗?

node.js - Redis:如何检查while循环中是否存在

javascript - 如何使用 Node js 将 json 发送到我的 View

javascript - 如何仅选择 Mongoose.find 中数组的一个元素