-2
let positionSettings = require('setting');

function getSetting(element) {
    let setting;
    positionSettings.find({element: element}, function (err,docs) {
        console.log(docs[0].current); // output the value
        setting = docs[0].current;
    });
    return setting;
}

$(document).on("click", "#save" , function(e) {
    console.log(getSetting("abc")); // Output undefined
});

Why is the getSetting() function returning undefined. How can I achieve it.

david.pfx
  • 10,520
  • 3
  • 30
  • 63

1 Answers1

2

Because it's an async function, you can't mix async and sync functions this way, try something like this:

let positionSettings = require('setting');

function getSetting(element, callback) {
    positionSettings.find({element: element}, (err,docs) => {
        let setting;
        console.log(docs[0].current); // output the value
        setting = docs[0].current;
        callback(setting);
    });
}

$(document).on("click", "#save" , (e) => {
    getSetting("abc", (setting) => {
       console.log(setting);
    });
});

The fact is that you can't be sure that the data will be avaible after the function call, the only place that you have this sure is inside the callback.

And just a hint, use arrow functions to declare anonymous functions.

Gabriel Carneiro
  • 643
  • 5
  • 16