I need to run a SQL SELECT statement and store the results. Then I need to pass those results into a function and create a graph based on the data points given. See code below.
var dataKWhr = getCoverageAndKWhr();
console.log(dataKWhr);
createGraph(dataKWhr);
console.log("Created graph");
The getCoverageAndKWhr function starts running but the rest of the original function continues with the log statement and createGraph. This fails because dataKWhr is undefined at this point since its value has not been returned from getCoverageAndKWhr().
I'd rather not put in a delay of a fixed number of seconds. Is there a way to wait for the first line to finish before proceeding?
This is a PhoneGap application with jQueryMobile. Currently testing on Android.
-
1You will need to pass a callback function to getCoverageAndKWhr() in order for this to work the way you want.Errol Fitzgerald– Errol Fitzgerald2013年10月29日 22:52:18 +00:00Commented Oct 29, 2013 at 22:52
-
If getCoverAndKWhr has any asynchronous code in it, you will need a callback function as @ErrolFitzgerald said.markasoftware– markasoftware2013年10月29日 23:21:23 +00:00Commented Oct 29, 2013 at 23:21
-
possible duplicate of getting a Webkit executeSql transaction to return a valueCL.– CL.2013年12月07日 23:10:46 +00:00Commented Dec 7, 2013 at 23:10
3 Answers 3
It's hard to tell what really going on without the code behind the getCoverageAndKWhr function.
Maybe some execution path doesn't return a value.
getCoverageAndKWhr could also be executed asynchronously. If it's the case, you must either find a way to transform getCoverageAndKWhr into a synchronous call or pass a callback function that will be invoked once the execution of getCoverageAndKWhr has completed.
1 Comment
Any I/O operation is going to be async, for certain. Any calls to SQLite/WebSQL DB's will have callbacks as part of their construction. You'll need to make use of them. (And then, when you learn to hate the callback design pattern, you may wish to convert to Promises.)
Comments
I've found that when you're programming in Javascript, it's easier to just always assume that every function is asynchronous. That's why stuff like this is a no-no:
var dataKWhr = getCoverageAndKWhr();
createGraph(dataKWhr);
You need to use callbacks, it's the only realistic way to make sure that your variable will populate before it's used. So it should look more like this:
getCoverageAndKWhr(createGraph);
And I don't know what's in getCoverageAnKWhr, but if you're making an ajax call in there it would look something like this:
function getCoverageAndKWhr(callBack) {
$.ajax({
type: 'GET',
//whatever else
success: function (data) {
callback(data.KWhr);
}
});
}