[英]calling a synchronous function (with call back) in foreach with the help of async.each
Sorry if my question seems simple to you! 对不起,如果我的问题对你来说很简单! I'm so new to Node and callbacks! 我是Node和回调的新手! I have an async function (with a callback) called "find", also I have a an array which is called models; 我有一个叫做“find”的异步函数(有一个回调函数),我也有一个叫做模型的数组; so I want to synchronously call this "find" function with each model in models and append the results in resultFound: 所以我想与模型中的每个模型同步调用这个“查找”函数,并将结果附加到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!): 这是我的尝试(我相信在st.find()中返回是错误的;但我刚刚提到我尝试给你一个洞察我正在尝试做的事情!):
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;
});
}
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. async
的方法会将回调function
传递给iterator
,在本例中为find()
,它希望调用它来知道何时继续。
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. 但是, async.each()
未定义为期望将data
提供给回调。
A method that will accept data
is async.map()
, which will already create a new collection that you can use as resultFound
. 接受data
方法是async.map()
,它已经创建了一个可以用作resultFound
的新集合。
var models = ["test1", "tes2"];
async.map(models, find, function (err, resultFound) {
if (err) {
res.json(400, err);
} else {
res.json(200, resultFound);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.