Not able to push data in user array. Promise not getting resolved

Viewed 32

I'm trying to send this array of authenticated users in an array to display connected accounts. Somehow it's not getting pushed into the users array. Probably promise is not getting resolved. However I'm able to see the response in the console.

async function getInstagramUserDetails() {
  let users = [];
    new Promise((resolve) => {
      window.FB.api("/me/accounts", (response) => {
        if (response?.data?.length) {
          
          response.data.map((account) =>      // response.data is the array of authenticated users associated with this account having id and access_token to get other details required for below API
            window.FB.api(
              `/${account.id}?fields=name,username,instagram_business_account&access_token=${account.access_token}`,
              (res) => {
                console.log(res)          // Able to see this object in the console
                const authUser = resolve(res)
                users.push(authUser);
              }
            )
          );
        } else {
          window.FB.api("/me", (response) => {
            const authUser = resolve(response)
            users.push(authUser);
          });
        }
      });
    });
    console.log("User", users);           // This is still an empty array 
    return users;
}

I even tried doing users.push(res) without resolving it like resolve(res) since I was getting the res object from the API. But it's not pushing it. What can be done or is there any other way to do that ?

1 Answers

Some issues:

  • async is not useful unless you use await in that function.
  • calling resolve multiple times has no effect. Only the first call counts
  • resolve always returns undefined, so assigning that to authUser is not very helpful
  • map returns an array, which you don't use. Either don't use .map or use the returned array

Things become easier if you first promisify the FB.api function:

const asyncApi = (...args) => new Promise(resolve => window.FB.api(...args, resolve));

And then:

async function getInstagramUserDetails() {
    const data = (await asyncApi("/me/accounts"))?.data;
    const users = await Promise.all(data?.length
        ? data.map(({id, access_token}) => 
            asyncApi(`/${id}?fields=name,username,instagram_business_account&access_token=${access_token}`)
          )
        : [asyncAapi("/me")]
    );
    console.log("Users", users);
    return users;
}    
Related