1

I want to offer a synchronous helper function in JavaScript that returns a simple string. Inside that function I have to query a SQLite database, which works with promises. What's the recommended way to synchronize async calls?

function getToken() {
    console.debug("getToken called");

    var deferred = $q.defer();

    var db = sql.getDb();
    db.executeSql('SELECT token from system LIMIT 1', [],
        function(result) {
            if (result.rows.length === 0 || !isTokenFormatValid(result.rows[0].token)) {
                deferred.resolve('');
            } else {
                deferred.resolve(result.rows[0].token);
            }
        }, function(error) {
            console.error();
            deferred.reject(Error('SQL: Not able to query token in system table. ' + error));
        });

    return deferred.promise;
}

Helper function:

function getTokenHelper() {
    // Todo: return token synchronously
}

The processing order is more complex but simplified in this post. Unfortunately I need a synchronous return value because the consumer is not able to handle promises.

dannyyy
  • 1,784
  • 2
  • 19
  • 43
  • 2
    You _can't_ return a result from a asynchronous function, synchronously. – Cerbrus Dec 07 '15 at 09:05
  • use callback function – Rana Ahmer Yasin Dec 07 '15 at 09:06
  • 1
    *"Unfortunately I need a synchronous return value because the consumer is not able to handle promises."* - Not really, you just need to invoke the synchronous consumer in the callback of the promise. Whether you say `promise.then(syncFunction)` where `syncFunction` is your function that doesn't take a promise, but a value, it should work without any problem. – Tomalak Dec 07 '15 at 09:12
  • 1
    Why you want a synchronous function when you are using AngularJS? All the pain of asynchronous functions is borne by AngularJS. You just need to make sure that you are resolving / rejecting promises properly. Rejection is very useful when you have higher priority for handling user interaction than waiting for promise to be resolved by some asynchronous operation. – domino_katrino Dec 07 '15 at 09:23
  • Thank you guys. I reorganized my code to deal with async. Question could be closed. And also thanks for linking to the similar question, which has very good explanations. – dannyyy Dec 07 '15 at 10:23

0 Answers0