简体   繁体   中英

How can we use inner variable from function calling in node js at outside?

var limit = 0;

Settings.find({ settings: "settings" }, function (err, docs) {
    limit=docs[0].keywords;  //6
    console.log('Limit from Inner : ' + limit);
});

console.log('Limit from Out : ' + limit);

It will give me output like : "Limit from Out : 0 Limit from Inner : 6"

I want call inner first and out put like : "Limit from Out : 6 Limit from Inner : 6"

Node.js is async, console.log('Limit from Out : ' + limit); is executed before the callback of Settings.find() is invoked.

if you must do what you described, you can use some control flow library such as https://github.com/caolan/async and do something like:

var limit = 0;

async.series([
    function(callback) {
        Settings.find({ settings: "settings" }, function (err, docs) {
            limit=docs[0].keywords;  //6
            console.log('Limit from Inner : ' + limit);
            callback(err);
        });
    }
], function(err) {
    console.log('Limit from Out : ' + limit);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM