【问题标题】: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? [duplicate]如何从包含 Promise 和 .then 的函数返回对象,以及如何在另一个函数中获取返回值? [复制]
【发布时间】:2021-07-27 08:20:42
【问题描述】:

如何从包含 Promise.then 的函数返回对象;以及如何在另一个函数中从该函数获取返回值?这是包含 Promise 的函数,我要返回的对象是 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; 
}

这是我想要获得回报的函数:

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
    }
}

我只是无法返回并从该函数中获得返回,其他一切正常。请帮忙

【问题讨论】:

    标签: javascript mongodb promise return es6-promise


    【解决方案1】:

    在顶层return new promise 的主函数中,并在解决obj promise 时将其解析并将其存储在newVarible 中。 然后使用promise.all("newVarible") 之后,您将能够在任何地方解决promise 后获取obj 的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-29
      • 2018-05-08
      • 2018-10-07
      • 2020-03-28
      • 2021-06-23
      • 2019-10-13
      相关资源
      最近更新 更多