简体   繁体   中英

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! 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;
        });
   }

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);
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM