Jason Khalili
Jason Khalili

Reputation: 101

Express: How to wait for a function to complete before calling something

I'm having an issue in Express. The following piece of code finds all the value in the pokemon collection and one by one, checks another collection to find matches. However, the code reaches res.send(documents) before all the items are finished inserting (display.insert(docs)). I know this is because of the way node works asynchronously, but I can't find a way to get past this issue. How can I ensure all of the documents get inserted?

pokeRouter.get('/sightings/:type([a-z]+)', function(req, res) {
display.deleteMany({}, function(err, bool) {
    if (err) throw err;

    if (bool) {
        pokemon.find().each(function(err, item) {
            if (err) throw err;

            if (item == null) {
                display.find().toArray(function(err, documents) {
                    if (err) throw err;

                    res.send(documents);
                })
            } else if ((req.params.type == item.type1) || (req.params.type == item.type2)) {
                sightings.find({
                    pokedex_id: item._id
                }).toArray(function(err, docs) {
                    if (docs == null) {
                        return null;
                    } else {
                        display.insert(docs);
                    }
                });
            }
        });
    }
});
});

Upvotes: 0

Views: 282

Answers (2)

David
David

Reputation: 1159

without using Promises or async module, you can refactor your code to have documents variable outside the async code and accumulate all the insertable items, and in your async code you would have some type of check (if everything is inserted) then I would call res.send(documents)

Upvotes: 0

Vincent Schöttke
Vincent Schöttke

Reputation: 4716

Your display.insert(...) function is probably also async. So the function inside the find().each(...) is returning before the insert is finished.

I highly recommend converting your the callbacks to Promises or use the async module to handle your async stuff.

Upvotes: 2

Related Questions