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 trial

JavaScript Asynchronous Programming with JavaScript Understanding Promises Promises Review

Alexander Perry
seal-mask
.a{fill-rule:evenodd;}techdegree
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 = [];

fetch(apiLink);
.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.