Home > database >  Unable to extract resolved value from async function
Unable to extract resolved value from async function

Time:12-03

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.

CodePudding user response:

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

const token = await Reddit.getAccessToken();

...

const userID = await Reddit.getCurrentUserId();
  • Related