I am trying to retrieve a single value from a Google Fusion table but am having problems doing so due to the asynchronous nature of the call. Any ideas how to do this? Here is what I have tried so far:
function getVal() {
var queryText = encodeURIComponent(query);
var gvizQuery = new google.visualization.Query(
'http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
gvizQuery.send(function (response) {
var dt = response.getDataTable()
alert(dt.getValue(0, 0)); // Works, returns a value
return dt.getValue(0, 0);
});
var value = getVal(); // Undefined
I will answer to the question that you have asked in the comments as that is more clear and I guess that's the problem you are looking to solve.
Use a Javascript Promise to handle such Async calls. (An overview of JS promise).
A promise will help you to wait for the response and then do operation on the same.
One example-
if (window.Promise) {
console.log('Promise found');
var promise = new Promise(function(resolve, reject) {
var request = new XMLHttpRequest();
request.open('GET', 'http://api.icndb.com/jokes/random');
request.onload = function() {
if (request.status == 200) {
resolve(request.response); // we got data here, so resolve the Promise
} else {
reject(Error(request.statusText)); // status is not 200 OK, so reject
}
};
request.onerror = function() {
reject(Error('Error fetching data.')); // error occurred, reject the Promise
};
request.send(); //send the request
});
console.log('Asynchronous request made.');
promise.then(function(data) {
console.log('Got data! Promise fulfilled.');
document.getElementsByTagName('body')[0].textContent = JSON.parse(data).value.joke;
}, function(error) {
console.log('Promise rejected.');
console.log(error.message);
});
} else {
console.log('Promise not available');
}
Your example should looks something similar to this-
function getVal() {
var promise = new Promise(function(resolve, reject) {
var queryText = encodeURIComponent(query);
var gvizQuery = new google.visualization.Query(
'http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
gvizQuery.send(function (response) {
var dt = response.getDataTable()
resolve(dt.getValue(0, 0));
});
reject(false);
}
}
var value = getVal();
Please read on Javascript Promises, it will help you a lot.