0

From my code, I want the value in _status variable after query and write file from MongoClient.connect, but I get NULL from return _status. How can I pass the value outside the function? Thank you for your answer.

function query(domain)
{
        var _status;
        MongoClient.connect(url, function(err, db) {
                if (err) throw err;
                db.collection("zone").find({"name" : domain}).toArray(function(err, result) {
                        if (!err) {
                                fs.writeFile('/root/'+domain+'.txt', result, function (err) {
                                        if (err) throw err;
                                });
                                _status = "success";
                        }
                        else {
                                _status = "fail";
                        }
                });
                db.close();
        });
        return _status;
}
Uzair A.
  • 1,586
  • 2
  • 14
  • 30
Anurak Jairak
  • 25
  • 1
  • 6
  • You should checkout this Stack Overflow Discussion:
    https://stackoverflow.com/questions/32631790/nodejs-returning-result-on-async-result
    – nityanarayan44 Feb 07 '18 at 07:43

2 Answers2

1

You are calling asynchronous functions( MongoClient.connect, .find) inside your function query, and trying to get the result(_status) synchronously. This does not work. You can use a callback based approach or a promise based approach to let the value of _status known to the caller.

Please refer here for more on promises.

Skyler
  • 656
  • 5
  • 14
0

try something like that

function query(domain, callback)
{
    var _status;
    MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        db.collection("zone").find({"name" : domain}).toArray(function(err, result) {
            if (!err) {
                fs.writeFile('/root/'+domain+'.txt', result, function (err) {
                        if (err) throw err;
                });
                _status = "success";
            }
            else {
                _status = "fail";
            }
            callback(_status);
        });
        db.close();
    });
}

query(domain, (status) => {
    // Synchronous
    // do something
    console.log(status);
});
groms
  • 14