Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to extract resolved value from async function

I’ve created a function to get the current user’s data from the Reddit API, as part of a Reddit object with multiple functions.

async getCurrentUserId() {
        if (userID) return userID;

        const token = await Reddit.getAccessToken().then(val => {
            return val;
        })
        const url = "https://oauth.reddit.com/api/v1/me"
        const headers = {
            "Authorization": `Bearer ${token}`,
            "User-Agent": "blablabla",
        };

        const response = await fetch(url, { headers: headers });
        if (response.ok) {
            const jsonResponse = await response.json();
            return jsonResponse.name;
        }
    },

However, when I try and extract the data, I keep getting a promise rather than the resolved value, and I can’t seem to be able to figure it out.

const userID = Reddit.getCurrentUserId().then(val => {
  return val;
}) // returns "Promise {<pending>}"

Assistance with this would be appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You either need to do your logic inside .then(), or simplify by using await:

const token = await Reddit.getAccessToken();

...

const userID = await Reddit.getCurrentUserId();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading