0

I can't get my head around how to return the value from uniqueCheck() to isValid. I've added in a setTimeout to simulate the async operation.

function isValid(data) {

    uniqueCheck(data, function(val) {
        return val;
        //true
    });
    // need the value here
}

function uniqueCheck(data, cb) {

    // do something with data async
    setTimeout(function () {

        cb(true)

    }, 1000);

}

console.log(isValid("some data"));
js2015
  • 45
  • 5

2 Answers2

0

you have to return the result through an callback function

function isValid(data, callback) {

    uniqueCheck(data, function(val) {
       callback(true);
        return val;

        //true
    });
    // need the value here
}

function uniqueCheck(data, cb) {

    // do something with data async
    setTimeout(function () {

        cb(true)

    }, 1000);

}
//console.log(isValid("some data"));
isValid("some data", function(value){
    console.log(value);
});
thanhpk
  • 3,900
  • 4
  • 29
  • 36
0

To use asynchronous calls in your code you can use Promises or for example if you use jQuery you can make use of Deferred object.

//async function using $.Deferred
function asyncFunction(){
    var dd = $.Deferred();
    setTimeout(function(data) {
        dd.resolve('loaded');
    }, 500);
    return dd.promise();
}

//somwhere in your code
asyncFunction().then(function(value){
    //do stuff when Deferred object is resolved
    //value = 'loaded'

})

in your code:

function isValid(data) {
  uniqueCheck(data).then(function(){
    //value is available here

  });
    // but not here
    //because this code is executed earlier then callback
}

function uniqueCheck(data, cb) {
var dd = $.Deferred();
    // do something with data async
    setTimeout(function () {
        cb(true)
    }, 1000); 
 return dd.promise();
}
shershen
  • 9,875
  • 11
  • 39
  • 60
  • Thanks for this. I'm trying to get my head around achieving this result without promises, just callbacks (if possible) – js2015 Feb 20 '16 at 13:58
  • with callbacks or promises - anyway it's impossible to have value in the place where you have ' // need the value here'. By any method you use your result will be inside of a closure, one level of brackets deeper, so to say. One more option if you have several functons like this - publisher/subscriber pattern - https://davidwalsh.name/pubsub-javascript, but it also adds additional level – shershen Feb 20 '16 at 14:12