node.js - 如何在 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
解决方案
您的问题是因为 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以获取更多信息
希望能帮助到你。
推荐阅读
- mysql - 为什么我的 rake 任务在测试运行期间无法连接到我的 MySQL 实例?
- r - 如何保存我的 Rstudio 工作区的状态
- javascript - ECONNREFUSED - node.js、passport.js、create-react-app、自定义中间件
- php - PHP - 在 mysqli 字符串结果中使用变量
- python-3.x - Python 桌面应用程序 - 打包
- node.js - MongoDB 事务无法按预期工作 - 当“订单项目”同时更新时,“订单”文档的总价格不正确
- reactjs - 使用 Kubernetes nginx 入口规则时,JS 文件未加载到应用程序
- python - 如何在mac中删除多个文件名的前n个字符
- python-3.x - 如何迭代python列表以获取映射到不同键的增量日期周期
- powershell - 是否可以每次通过 Powershell 中的 For-Loop 重新编译变量