Search code examples
javascriptcordovabarcode-scanner

How can i set a local Variable in Javascript in a function i used as parameter?


I've got a problem in Javascript using Barcodescannerplugin for Phonegap in an Android Application.

The plugin I use is bringing a small Javascript to enable using the Barcodescanner in my Phongap application. But in my opinion the interface of the provided javascript functions isn't that optimal, cause I don't want to do an errorhandling at every position where I use these methods.

That's why I tried to make that interface more easy in the way, that I just have to call a method scanBarcode() and the calling script is getting the text from the scanned or nothing, if something fails. Here is the code:

function scanBarcode(){
    var resultText = '';
    window.plugins.barcodeScanner.scan( 
        function(result) {
            if (!result.cancelled){
                resultText = result.text;
            }
        },
        function(error) {
            alert("Scanning failed: " + error);
        }
    );
    return resultText;
}

The plugin I use can be found at: Github Phonegap Plugins Android/BarcodeScanner

The result of my Method is always the same, an empty string. I think the reason is the variable scope, but I am not sure how to solve the problem.


Solution

  • The reason is because the window.plugins.barcodeScanner.scan method executes asynchronously - the success callback is not called until the method has returned.

    I'd recommend returning a Promise object from your method, so something like (using jQuery as an example):

    var result = $.Deferred();
    window.plugins.barcodeScanner.scan( 
        function(result) {
            if (!result.cancelled){
                result.resolve(result.text);
            }
        },
        function(error) {
            result.reject(error);
        }
    );
    
    return result;