Saeedeh
Saeedeh

Reputation: 295

how to handle async function that return promise?

I want to get a user from MongoDB. so I should use the async function to get the right result. but it return me [object , promise]. how can I use this data?

async function getUsers() {
    var allUsers = null;
    await MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        var dbo = db.db('mydb');
        dbo.collection("users").find({})
            .toArray(function(err, results) {
                if (err)
                    throw error;
                db.close();
                allUsers = results;
            });
    });
}


app.get('/user/', function(req, res) {
    MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        var dbo = db.db('mydb');
        var id = req.params.id;
                    var allUsers = getUsers();
             res.render('pages/user', {users: allUsers });
            db.close();
        });
});

Upvotes: 0

Views: 49

Answers (1)

jfriend00
jfriend00

Reputation: 707326

You are mixing up promises and plain callbacks. You need to pick one or the other and consistently use it. Here's how to code it with promises - using the promises that MongoDb can return if used in the right way:

async function getUsers() {
    const db = await MongoClient.connect(url);
    try {
        const dbo = db.db('mydb');
        const results = await dbo.collection("users").find({});
        return results;
    } finally {
        db.close();
    }
}


app.get('/user/', function(req, res) {
    getUsers().then(allUsers => {
        res.render('pages/user', {users: allUsers });
    }).catch(err => {
        console.log(err);
        // send some sort of error response here
        res.sendStatus(500);
    });
});

I removed the database operations from inside your route handler because they weren't actually doing anything and the db stuff was already inside of getUsers().

Upvotes: 2

Related Questions