如何在 LINE 聊天机器人中创建 profile.displayName return 名称
How to make profile.displayName return name in LINE chatbot
我开始使用 lib @line/bot.sdk 并想从函数和 return 中获取 displayName 但它没有 return displayName return 'undefined'
这是函数
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
但是函数 return 和 'undefined'
我也想 return displayName
你的问题是因为 JavaScript 是异步的,所以你不能只 return 异步函数中的值,你需要使用承诺或回调:
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
});
我建议您阅读这篇文章Understanding Asynchronous JavaScript以获取更多信息
希望对您有所帮助。
我开始使用 lib @line/bot.sdk 并想从函数和 return 中获取 displayName 但它没有 return displayName return 'undefined'
这是函数
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 但是函数 return 和 'undefined' 我也想 return displayName
你的问题是因为 JavaScript 是异步的,所以你不能只 return 异步函数中的值,你需要使用承诺或回调:
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
});
我建议您阅读这篇文章Understanding Asynchronous JavaScript以获取更多信息
希望对您有所帮助。