首页 > 解决方案 > 如何在 LINE 聊天机器人中使 profile.displayName 返回名称

问题描述

我开始使用 lib @line/bot.sdk 并想从函数中获取 displayName 并返回它,但它没有返回 displayName 它返回“未定义”

这是功能

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 可以获取 displayName 但函数返回“未定义”我希望它也返回 displayName

标签: node.jslinedialogflow-eschatbot

解决方案


您的问题是因为 JavaScript 是异步的,所以您不能只在异步函数中返回一个值,您需要使用 promise 或 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
});

我建议您阅读这篇文章了解异步 JavaScript以获取更多信息

希望能帮助到你。


推荐阅读