Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialMatthew Lee
6,715 PointsHow can I wait for a function to finish before continuing?
Hi,
I have a function that calls an API and parses and then loads data into an array.
How can I wait for this function to finish before continuing with the rest of the code which uses the loaded data?
Best, Matt
2 Answers
Caleb Kleveter
Treehouse Moderator 37,862 PointsI am not very fluent in Java, so I don't know the best way to do this, but typically you use what is called a callback function. A callback is a function that is passed into another function as a parameter. Here is some basic pseudo code:
function getDataFromURL(url, callback) {
// Get data here.
// Pass that data into the call back function
callback(data);
}
// Use the above function
getDataFromWeb("https://teamtreehouse.com/calebkleveter.json", function(data) {
// Use the data passed in from the callback
});
Matthew Lee
6,715 PointsI was stuck on this for a couple of days but I called the function (the one I wanted to run after getting data from the API) in runOnUiThread() inside the OnResponse().
Matthew Lee
6,715 PointsMatthew Lee
6,715 PointsThanks for the input!