0

I have to loop through an array of objects and modify one single property in each object. I modify this property with a function that connects to the Twitter API. My problem is that I must be using async and await wrongly because I am getting a promise pending.

This is my code:

getProfile:(req,res)=>{
        try {
           const userId=req.params.id 
           const profile=db.query('SELECT * FROM profiles WHERE user_id=?',
        [userId],async (err,result)=>{

            if(err) return res.status(404).send(err)

            const profiles= await result.map(  obj=>{

                const container={}
                container['name']=obj.profile_name
                container['desc']=obj.profile_desc
                container['twitter']=  connectTwitt.getTwitt(obj.twitt)//calls to api
                return  container
            })
            console.log(profiles)// promise pending
            res.send(profiles)

This is the structure of the array of object that I am mapping:

[
 {profile_name:`Elon Musk`, profile_desc:'enterpreneur',twitt:636465}
]
kiner_shah
  • 3,939
  • 7
  • 23
  • 37

1 Answers1

0

Yes, you are using the async/await syntax a little bit incorrectly.

Right now, you are calling await on the Array.map() method. However, that method is not promise-based.

Instead, you have to add the await keyword to the getTwitt() method, and await for all promises to complete.

With those changes, it should look like below.

const profiles = await Promise.all(result.map(async (obj) => { // This line has been modified
  const container = {};
  container["name"] = obj.profile_name;
  container["desc"] = obj.profile_desc;
  container["twitter"] = await connectTwitt.getTwitt(obj.twitt); // This line has been modified.
  return container;
}));

Hopefully this helps with your <pending> issue!

Arnav Thorat
  • 3,078
  • 3
  • 8
  • 33
  • The function isn't declared `async`, you can't use `await` inside it. – Barmar Feb 05 '22 at 07:09
  • See https://stackoverflow.com/questions/63929347/why-is-my-function-returning-promise-pending?noredirect=1#comment113047163_63929347 – Barmar Feb 05 '22 at 07:10
  • Now I guess OPs next question will be how they can convert the array of Promises stored in `profiles` to an array of objects. – Nick Parsons Feb 05 '22 at 07:15
  • Thank you Promise.all worked and solved the issue. I just had to add async to the first callback function. –  Feb 05 '22 at 15:52