Calling synchronous function (with callback) in foreach using async.each
Sorry if my question seems simple to you! I am so new to Node and callbacks! I have an async (with a callback) function called "find", also I have an array called models; so I want to call this function "find" synchronously with every model in the models and add the results to the resultFound:
I appreciate your help! Please let me know if you need more clarification.
st.find(param1, model, param2, param3, function (err, data) {
if (err) {
res.json(400, err);
} else {
res.json(200, data);
}
});
Here's my attempt (I believe the return to st.find () is wrong, but I just mentioned my attempt to give you an idea of ββwhat I'm trying to do!):
var models = ["test1", "tes2"];
var resultFound = [];
async.each(models, find, function (err, data) {
resultSearch.push(data);
});
function find(model) {
st.find(param1, model, param2, param3, function (err, data) {
return data;
});
}
source to share
async
the methods will pass a callback function
to iterator
, in this case find()
, which it expects to know when to continue.
function find(model, callback) {
st.find(param1, model, param2, param3, function (err, data) {
callback(err, data);
});
// or possibly just:
// st.find(param1, model, param2, param3, callback);
}
Although async.each()
not defined to wait data
for a callback.
A method that takes data
, async.map()
which will already create a new collection that you can use as resultFound
.
var models = ["test1", "tes2"];
async.map(models, find, function (err, resultFound) {
if (err) {
res.json(400, err);
} else {
res.json(200, resultFound);
}
});
source to share