1

Long story short. I'm trying to learn javascript. And i've been googling for about 4 hours straight right now. And i cant find the answer to my current problem, so i'm assuming i'm looking at this the wrong way.

I'm trying to create a slackbot. The bot is connected, and can look for messages so that part is working.

I've (tried to)create(ed) a function that gets the userID of everynew message based on the name i set in. In my mind this function returns the userID, and that i can later down the code check if userID is in message.text, if it is do something.

I'm assuming it has something to do with that .then function. Can i even return data from that .then function? or can u just use that data inside of that function.

I have several return functions as i was trying to just return it from wherever u could.

function getuserid(botname){
    
    var id = ''

    var getbotid = bot.getUsers();
    getbotid.then(function(value){ 
        for(var i=0;i<value.members.length;i++){
            if(value.members[i].name == botname){
                id = value.members[i].id
                console.log(id);//this logs what i want.
                return id
                
            }
        } return id 
        
    })
    return id 
}

var botid = getuserid('jokester');
console.log(botid);
Smoearn
  • 21
  • 4
  • Do yourself a favor and don't rely on the [automatic insertion of semicolons](https://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi) because this can have [unintended side-effects](https://stackoverflow.com/questions/34950322/use-of-semicolons-in-es6) – Andreas Dec 31 '18 at 15:28
  • Thank you @Andreas – Smoearn Dec 31 '18 at 15:34

1 Answers1

0

I'm not sure but in my experience, if you return getbotid() then actually you return a promise and you can use it .

function getuserid(botname){

var id = ''

//************Here I return getbotid 
return bot.getUsers().then(function(value){ 
    for(var i=0;i<value.members.length;i++){
        if(value.members[i].name == botname){
            id = value.members[i].id
            console.log(id);//this logs what i want.
            return id

        }
    } return id 

})
return id 
}
//Now you can use it 
getuserid('jokester').then(id => console.log(botid));
MBehtemam
  • 7,865
  • 15
  • 66
  • 108
  • @Smoearn could you try my updated answer and then insert some `log` for value and other thing and update you question. thanks. – MBehtemam Dec 31 '18 at 15:37
  • getuserid('jokester').then(botid => console.log(botid)); prints out what i want. But i really want to store that inside a variable so that i can use it at a later time to do checks @MBehtemam – Smoearn Dec 31 '18 at 15:43