javascript - 如何将 ctx 范围传递给外部函数?
问题描述
我有这段代码,我被迫将函数 checkIfMember 保留在上下文中,以将其作为参数传递给另一个函数。因为否则,我不能调用 ctx. 它以这种方式工作,但我想让函数 checkIfMember 分开,但问题是 ctx 将是未定义的。我将如何传递上下文或允许我分离函数的东西?
bot.command('raintest', async (ctx) => {
//check if an user has a member rank in the group
function checkIfMember(uid, cid){
return ctx.getChatMember(uid, cid).then(data =>{
if(data.status == "member"){
return true;
}else{
return false;
}
}).catch(err =>{
console.log(err)
})
}
let chatid = ctx.message.chat.id
let myId = ctx.update.message.from.id
let message = ctx.message.text.toString()
message = message.split(" ")
let numberOfUsers = message[1]
let tipAmount = message[2]
let totalAmountToTip = numberOfUsers * tipAmount
if (tipAmount != undefined && numberOfUsers != undefined) {
if (tipAmount == 0 || numberOfUsers == 0) {
ctx.reply("Users or Balances can't be 0 ⛔️!!")
} else {
if (Number(numberOfUsers) > 10) {
ctx.reply("You cant rain for more than 10 users ⛔️!!")
} else {
userCommon.userHasEnoughtBalance(myId,chatid, totalAmountToTip).then(res => {
if (res) { //THERE I PASS CHECKIFMEMBER AS A FUNCTION
userCommon.returnMembers(chatid, checkIfMember,numberOfUsers).then(res => {
if (res[0] == false) {
ctx.reply("⛔️⛔️ There are only " + res[1] + " users in the system.")
} else if (res[0] == true) {
let tipedUsers = []
var userArray = res[1]
解决方案
将 ctx 注入你的函数:
function checkIfMember(ctx) {
return function (uid, cid){
return ctx.getChatMember(uid, cid).then(data =>{
if(data.status == "member"){
return true;
}else{
return false;
}
}).catch(err =>{
console.log(err)
})
};
};
现在 checkIfMenber 是一个返回函数的函数。
然后,当您必须将其用作回调时:
userCommon.returnMembers(chatid, checkIfMember(ctx),numberOfUsers).then...
推荐阅读
- c++ - asio::io_context::run_one() 和 while()
- javascript - VanillaJS 到 VueJS 错误:Flickity 的坏元素:轮播
- r - 在一个数据框中连接多个数据框列表
- javascript - 如何安全地从任意 html 中提取文本内容
- java - java.util.Vector 中元素计数和元素数据的值不同
- r - 迭代地组合两个字符向量
- django - DPI-1047“libclntsh”无法打开共享对象文件:没有这样的文件或目录“
- .net - 如何修复 Visual Studio 2017 中的“无法加载 CLR”?
- powershell - notcontains 不适用于从 AD 组中提取的用户对象
- api - 访问权限不足:GET /me