Search code examples
node.jslinedialogflow-eschatbot

How to make profile.displayName return name in LINE chatbot


I start to use lib @line/bot.sdk and want to get displayName from function and return it but it didn't return displayName it return 'undefined'

Here is function

record:function(userID){
    client.getProfile(userID).then((profile) => {
            let name = profile.displayName
            let ID = profile.userId
            console.log('record Name : ' + name);
            return name
            //console.log('record ID : ' + ID)
            //console.log('record Pic : '+profile.pictureUrl )
            //console.log('record Status :'+profile.statusMessage)
        }).catch((err) => {
            return "Error"
      })  
}

console.log can get displayName but the function return with 'undefined' i want it to return displayName too


Solution

  • Your problem is because JavaScript is Asynchronous, so you can't just return a value inside a asynchronous function, you need to use a promise or callback :

    record: function(userID, callback){
        client.getProfile(userID).then((profile) => {
            // return your name inside a callback function
            callback(null, profile.displayName);
        }).catch((err) => {
            callback(err, null);
        })
    }
    
    // Call your function and get return 'name'
    record(userId, function(err, name) {
        if (err) throw err;
        console.log(name);
        // Continue here
    });
    

    I recommand you to read this article Understanding Asynchronous JavaScript to get more information

    Hope it helps.