This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
                                
                                    (6个答案)
                                
                        
                                2年前关闭。
            
                    
我想要一个函数返回“用户”集合中的内容。但是由于异步性质,函数返回的是未定义的。我如何等到mongodb将值赋给变量

function a(){
    var m;
    MongoClient.connect(URL).then( db => {
        db.db('mydb').collection('user')
        .find({}).toArray().then(result => {
            m=result;
            // return m wont help here
        }).catch(log);
    }).catch(log);
    return m;
}
console.log(m);

最佳答案

function b(m) {
    console.log(m);
}

function a() {
    MongoClient.connect(URL).then(db => {
        db.db('mydb').collection('user')
            .find({}).toArray().then(result => {

                b(result);

            }).catch(log);

    }).catch(log);

}

09-20 17:20