holler
holler

Reputation: 275

Promises in node.js

Aiming to get image urls for users found in a message history. Obviously after I loop through data.directMessages.map object image url values never make it to res.render('index', {data}) I'm convinced I need data.directMessages.map to perform all operations first and ONLY then have the result returned. Could you help me to figure out how?

It's my pseudo code:

app.get('/', (req, res) => {
   Promise.all(arrayOfPromises).
   then(data => {
       return {
           ...
           ...
           directMessages: ...
       }
   }).
   // HELP NEEDED HERE !!!
   then(data => {
       data.directMessages.map(info => {
           const getData = await getProfileDataById(info);
            info.profile_img_url = await getData.profile_img_url;
           });
           return data;
       // HELP END !!!
       }).then(data => {
           res.render('index', {data});
       })
    })

I'm thinking of doing this

const results = data.DirectMessages.map(async (info)=> {
    // do stuff and return results
});
Promise.all(results).then(data => data);

Would it be the right way to solve it?

Upvotes: 2

Views: 97

Answers (1)

Arif Khan
Arif Khan

Reputation: 5069

You may use async/await as following way(assuming that getProfileDataById(info) will return promise)

app.get('/', async (req, res) => {
    let data = await Promise.all(arrayOfPromises);
    data = {
        ...
        ...
        directMessages: ...
    };
    // Promise.all help you run parallel execution  
    const getData = await Promise.all(data.directMessages.map(info => getProfileDataById(info)));
    getData.forEach((profileData, i) => {
        data.directMessages[i].profile_img_url = profileData.profile_img_url;
    })
    res.render('index', {
        data
    });
})

Upvotes: 1

Related Questions