DEV Community

Discussion on: Javascript: How to access the return value of a Promise object

Collapse
 
r00tk1ll3r profile image
Monotheist

const address = fetch("jsonplaceholder.typicode.com/users/1")
.then((response) => response.json())
.then((user) => {
return user.address;
});

const printAddress = async () => {
const a = await address;
console.log(a);
};

let d = printAddress();
console.log(d); <-------- how do I do this? this still returns a Promise { }
I want to access return value from printAddress()

Collapse
 
ramonak profile image
Katsiaryna (Kate) Lupachova

That's the whole point! You can use the return value from the Promise object ONLY in a async function.

You should do all the stuff that you'd like to do with the return result in a printAddress() async function.

Collapse
 
thechallengerr profile image
thechallengerr • Edited

But what if i had to take the return value of Promise to use as data to render ?
my case is that : I have to query database to get the link for 'src' attribute ? I use mongoosejs
Hope you can explain . Thank You

async getEventThumb(event_slug) {
            let event_thumb = Event.findOne({ event_slug: event_slug }).then((event) => {
                if (event === null) {
                    return ""
                } else {
                    event_thumb = event.event_thumb;
                }

                return event.event_thumb;
            }).catch((err) => {
                console.error(err);
            });

            // console.log(event_thumb);

            return await event_thumb;
        }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
younglotushuncho profile image
younglotushuncho

i find a new solution

the best way to use a promise ...... use a promise inside a promise ...it will work