简体   繁体   English

如何使用ExpressJS和MongoDB使用Promise / Callbacks?

[英]How to use promises/callbacks using expressjs and mongodb?

I am really confused about how promises and async javascript work. 我对Promise和异步javascript的工作方式感到困惑。 I want to do a GET on /user and query mongo so that the result of the first query is processed in some way to form the query of the second query, and the result of that query be the query of the third query. 我想对/ user执行GET并查询mongo,以便以某种方式处理第一个查询的结果以形成第二个查询的查询,并且该查询的结果就是第三个查询的查询。

Basically I want the result of the final mongo result to be sent back to the client via res.send(result). 基本上,我希望最终mongo结果的结果通过res.send(result)发送回客户端。

What's the proper way of doing this so that the client gets a 200 OK back with the result of the third nested mongo query? 这样做的正确方法是什么,以便客户端通过第三次嵌套mongo查询的结果返回200 OK?

app.get('/user', function (req, res, next) {

    var query = {"isRegistered": false }

    db.collection('users', function (err, collection) {
        collection.find(query).toArray(function (err, result) {
            if (err) {
                console.log(err)
            }
            else {
                if (result.length > 0) {
                     // do some random processing 
                     var randomUser = result[Math.floor(Math.random() * result.length)] 
                    // do ANOTHER db query
                    query = {"age": randomUser.age}
                    collection.find(query).toArray(function (err,result) {
                         if (err) {
                            console.log(err)
                         }
                         else {
                           // do some other logic ...
                           query = {something}
                           collection.find(query).toArray(function (err,result) {
                               if (err) {
                                 console.log(err);
                               }
                               else {
                                  // FINALLY RETURN THIS RESULT
                                  res.send(result);
                                  next()
                               }
                           })
                         }
                    })
                }
            }
        });
    });

Assuming you're using the regular Mongo client for Node, it already returns promises for queries, meaning you can just return the next query and catch it in a then , or catch an error at the end with catch . 假设您正在为Node使用常规的Mongo客户端,它已经返回了对查询的承诺,这意味着您可以只返回下一个查询, thenthen捕获它,或者在最后用catch错误。

Untested, but something similar to this should work 未经测试,但与此类似的东西应该可以工作

app.get('/user', function (req, res, next) {

    var query = {"isRegistered" : false };
    var collection = db.collection('users');

    collection.find(query).toArray().then( result => {
        var randomUser = result[Math.floor(Math.random() * result.length)];
        var query2     = {"age" : randomUser.age};

        return collection.find(query2).toArray();
    }).then( result => {
        var query3 = {something : 'something'};

        return collection.find(query3).toArray();
    }).then( result => {
        res.status(200);
        res.send(result);
    }).catch( err => {
        console.log(err);
        res.status(500);
    });
});

Note that methods like toArray automatically returns a promise if no callback function is passed. 请注意,如果未传递回调函数,则类似toArray方法会自动返回promise。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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