Title: Await all Mongo queries with Node.js
Tags: node.js;mongodb;promise
Question: Code below has a flaw as I am getting array of ```undefined```:

```let filters = [];

async function getFilters(tiers) {

    return await Promise.all(

        tiers.map(async t =&gt; {
            let id = new ObjectId(t.filter);

            filters.push(
                await conn.collection('TierScheduleFilter').find({
                    _id: id
                }).toArray(function(err, filter) {
                    if (err || !filter) {
                        reject('no filter || error');
                    }

                    return filter;
                });
            );
        });
    );
}
await getFilters(tiers);
console.log(filters); // 4 filters =&gt; [ undefined, undefined, undefined, undefined ]
```

The code shall retrieve all filters but its all undefined values.

Comment: Is this all inside another async function? You can't declare `await`s outside async functions.

Comment: Something like `getFilters(tiers).then(x => console.log(filters))` (note: pseudocode) will possibly work for you. Because your code is no longer synchronous, your console.log is being run before the rest of your code has a chance to complete.

Comment: ... if you don't force the console.log to run _after_ the getFilters call is complete, it will always print undefined as that stuff hasn't finished evaluating at that point in the code.


Here is another answer: This one seems to be a proper approach:

```let filters = [];
    async function getFilters(tiers) {
        return await Promise.all(
                tiers.map(async t =&gt; {
                        let id = new ObjectId(t.filter);
                        try {
                            return await conn.collection('TierScheduleFilter').findOne({ _id: id })
                        } catch (e) {
                            return e;
                        }
                }))
    }
```


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 3, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2019:00:11/06/19', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<node.js><mongodb><promise>', 'Title': 'Await all Mongo queries with Node.js', 'ViewCount': 89, 'id': 58730612, 'user_AboutMe': '<p>10+ years of exp. building and integrating APIs, platforms, services, and applications.</p>\n<p>WebDevStack:</p>\n<ul>\n<li>(Backend) <strong>PHP, JS (Nest, Express)</strong></li>\n<li>(FrontEnd) <strong>HTML5, Vue, Angular, React</strong></li>\n<li>(DevOps) <strong>GCP, AWS</strong></li>\n<li>(Mobile) <strong>Flutter</strong></li>\n</ul>\n', 'user_AccountId': 16601072.0, 'user_DisplayName': 'matrixb51', 'user_Reputation': 57.0, 'user_Views': 16.0, 'user_id': 11996732.0}}