Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Asynchronous Programming with JavaScript Understanding Promises Promises Review

Alexander Perry
Alexander Perry
Front End Web Development Techdegree Student 11,395 Points

Returning values stored in promises?

I'm noticing that whenever we're using asynchronous methods, they never return anything. They always log something to the console or update HTML or something.

But what if our program wants to use the value pulled from an AJAX request for example? I know there's a rule about asynchronous methods not being able to return values to synchronous functions, but it feels like I'm missing something.

For example, if you made an HTTPS request of a web API, let's say Wikipedia's, and you were pulling the content of a page on Queen Elizabeth. Let's say you wanted to pull her age from the web and use it in a calculation somewhere else in your program. How would you do it?

Thank you in advance for any help!

2 Answers

Johnathan Guzman
Johnathan Guzman
7,432 Points

Hey Alexander,

To my understanding, you want to use the data retrieved from an API?

This is how I would approach this:

let apiStorage = [];

.then((res) => res.json())
.then((apiData) => {
    apiStorage = apiData

Then you can mess around with the data.

I hope this helped.

Hi Alexander Perry,

Maybe I’m not quite understanding the question that you’re asking, but asynchronous method can have return values. I would even go so far as to say that they usually have return values.

If I were to make an xhr to an API and the API returned to me Queen Elizabeth’s age, I would probably store it in a variable.

const age = await fetch(some-url)

I would then use the variable when I needed access to the age value returned from the API.

Hope this helps. And if I’ve totally misunderstood your question, let me know.