首页 > 解决方案 > 如何将 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]

标签: javascriptnode.js

解决方案


将 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...

推荐阅读