Search code examples
javascriptmongodbpromisereturnes6-promise

How to return an object from a function that contains a Promise and a .then and how to get the returned value in another function?


how can i return an object from a function that contains a Promise and a .then; and how can i get the returned value from that function, in another function? Here is the function that contains the Promise and the object that i want to return is obj:

function searchdb(user, key){
    var ok;
    const list = new Promise(function (resolve, reject) {
        MongoClient.connect(uri, function(err, db) {
            var dbc = db.db("chat");
            dbc.collection("chat_messages").find({$or: [ {user1: key, user2: user}, {user1: user, user2: key} ]}).toArray(function (err, result){
                if(err) {
                    reject(err);
                } else {
                    resolve(result);         
                }
                if(result[0].user1 == key){
                    ok = 1;
                }
                else{
                    ok = 2;
                }
            });
        db.close();
            
        });
        
    });
    var obj = {};

        list.then(result => {  
        if (ok == 1){
            obj[result[0].user1] = result[0].user2_seen;
        }else{
            obj[result[0].user2] =result[0].user1_seen;
        }
        console.log(obj);              <--------------- here its working
        }).catch(err => console.log(err.message));

        return obj; 
}

And here is the function where i want to get the return:

function get(data){
    suser = data[0]
    obj = data[1];
    
    for (var i in obj){
        var key = Object.keys(obj[i])[0];

        var a = searchdb(suser, key);
        console.log(a);       <-------------- here its not working
    }
}

I just can't return and get the return from that function, everything else its working fine. Please help


Solution

  • In your main function at the top level return new promise and resolve it whenever obj promise is solved and store it in newVarible. Then Use promise.all("newVarible") after that you'll be able to get values of obj after the promise is being resolved anywhere.