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.