2

I currently have a backend developer supplying me with a bunch of messages with this sort of data

tasks = [
  {
    timestamp: <some timestamp>,
    message: 'asdfas fasdf asdf',
    uid: <slack user id>
  },
  {...},
  ...
]

I have a for loop displaying each message but I also want to include slack data. For that, I would need to hit the slack API with the id of each user to get the slack user data.

This is what my build_tasks method looks like:

let build_tasks = ( tasks ) => {
    let str = ''

    if ( tasks ) {
        tasks.data.forEach( async( task ) => {

            let poster = await get_slack_user_info( task.usr )

            str += `
                <a target='_blank' href="${ task.link }" class='task-container'>
                    <p class="time">${ new Date( task.ts * 1000 ).toLocaleTimeString( 'en-US', { hour: '2-digit', minute: '2-digit', hour12: true } ) }</p>
                    <p>${ task.message }</p>
                </a>
            `
        } )
    } else {
        str += `<p>No data</p>`
    }

    destination.innerHTML = str

}

This is what the get_slack_user_info is like:

let get_slack_user_info = ( uid ) => {

    let url = SLACK_USERS_API + `?token=${ SLACK_TOKEN }&user=${ uid }`

    return new Promise( resolve => {

        axios.get( url )
            .then( res => {
                resolve( res.data.profile )
            } )
    } )

}

The issue ( im assuming ) is that since I am await-ing for get_slack_user_info to fire, destination.innerHTML = str gets fired and nothing gets rendered on my screen.

Any help?

Thanks.

Syn
  • 938
  • 1
  • 10
  • 21
  • https://api.slack.com/web slack API docs, in case you need more info – Qui-Gon Jinn Sep 24 '19 at 18:07
  • Im pretty sure its something to do on my end and not something to do with slack. I have a feeling it has something to do with async stuff with js. SInce it takes a bit to grab data, the str variable stays empty – Syn Sep 24 '19 at 18:09
  • Try to debug line by line your code its gonna help to see when you receiving the response. – Qui-Gon Jinn Sep 24 '19 at 18:41
  • Also avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it) in `get_slack_user_info`! – Bergi Sep 24 '19 at 20:34

0 Answers0