Reputation: 1984
Sorry if my question seems simple to you! I'm so new to Node and callbacks! I have an async function (with a callback) called "find", also I have a an array which is called models; so I want to synchronously call this "find" function with each model in models and append the results in 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 is my try (I believe having a return in st.find() is wrong; but I just mentioned my try to give you an insight of 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;
});
}
Upvotes: 3
Views: 109
Reputation: 123423
async
's methods will pass a callback function
to the iterator
, in this case find()
, that it expects to be called 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);
}
Though, async.each()
isn't defined to expect data
to be provided to the callback.
A method that will accept data
is 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);
}
});
Upvotes: 2