0

I need to return a boolean from a function t, like this:

    function(t){   
        //Do Something 
        return resultBool;
    }

But I when I have an async function (CasperJS) that determines the outcome, how would I do this using a callback? I tried something like this, but it doesnt seem to work (I think the function is simply returning the return value of t.withFrame, which is always true).

function(t){    
            function findElementInFrame(callback)
            {
                try{
                    t.withFrame("etravelframe", function(){
                        if(t.exists('#outFlight1------') == true){             
                            callback(true);           
                        } 
                        else{                                               
                            callback(false);                            
                        } 
                    });
                } catch(err){
                    //return false;
                }
            }            


            return findElementInFrame(function(bool){return bool;});

        }
Thomas
  • 2,070
  • 3
  • 16
  • 21
  • Possible duplicate of: http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call Your questions doesn't deal with AJAX in particular, but the issue of using a value from an asynchronous call is the same. – George Sep 20 '13 at 14:11

1 Answers1

2

Your function needs to be async as well. So ether also accept a callback, like this.

function (t, callback) {
    try {
        t.withFrame("etravelframe", function () {
            if (t.exists('#outFlight1------') == true) {
                // Callbacks usually take the error as first parameter.
                // So by using null as first parameter, we notify the callback that here is no error. 
                // And that the result (if any) is available in the second argument.
                callback(null, true);
            } else {
                callback(null, false);
            }
        });
    } catch (err) {
        // also use the callback, async functions should work consistently
        callback(err);
    }
}

Or create a deffered object and return a promise.
Like so:

function (t) {
    var deferred = jQuery.Deferred()
    try {
        t.withFrame("etravelframe", function () {
            if (t.exists('#outFlight1------') == true) {
                deferred.resolve(true);
            } else {
                deferred.resolve(false);
            }
        });
    } catch (err) {
        deferred.reject(err);
    }
    return deferred.promise();
}
Willem D'Haeseleer
  • 19,661
  • 9
  • 66
  • 99