如何正确地执行createReactionCollection [英] How to properly do a createReactionCollection

查看:100
本文介绍了如何正确地执行createReactionCollection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直想在用户按下Check或X的反应时创建一个事件.尽管,当我使用该函数时,收到消息对象不存在的错误.

I've been wanting to create an event when a user presses a reaction that is a Check or X. Although, when I use the function I get an error that it doesn't exist for the message object.

我已经从awaitReactions回来了,它没有用.

I've already from awaitReactions back to this and it hasn't worked.

我对messageSent对象做了一个console.log,我得到了这个Promise { <pending> }

I did a console.log to the messageSent object and I got this Promise { <pending> }

var messageSent = user.send({embed})
    .then(function (message) {
         message.react('✅')
         message.react('❎')
     });
messageSent.createReactionCollection(r => ['✅','❎'].includes(r.emoji.name))
     .on('collect', r => {
         if (r.emoji.name == '✅') {
             user.send("Verified! ✅")
          } else if (r.emoji.name == '❎') {
             user.send("Canceled! ❎")
          }
      });   
  }

TypeError: messageSent.createReactionCollection is not a function
    at app.post (C:\Users\teddy\Desktop\Verify\app.js:46:25)
    at Layer.handle [as handle_request] (C:\Users\teddy\Desktop\Verify\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\teddy\Desktop\Verify\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\teddy\Desktop\Verify\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\teddy\Desktop\Verify\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\teddy\Desktop\Verify\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\Users\teddy\Desktop\Verify\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\teddy\Desktop\Verify\node_modules\express\lib\router\index.js:275:10)
    at expressInit (C:\Users\teddy\Desktop\Verify\node_modules\express\lib\middleware\init.js:40:5)
    at Layer.handle [as handle_request] (C:\Users\teddy\Desktop\Verify\node_modules\express\lib\router\layer.js:95:5)

推荐答案

同步与异步

假设您打算接朋友去参加体育赛事.您不确定他们什么时候要您来,因此您可以打电话给他们并询问他们.他们考虑了一会儿,然后告诉您一段时间.您获得了所需的信息,因此您挂断了电话.用编程术语来说,这将是同步代码的一个示例(有时在Node.js中被认为是普通"代码).

Sync vs Async

Say you're planning on picking your friend up to go to a sporting event. You're not sure when they want you to come, so you call them on the phone and ask them. They think about it for a while, and then tell you a time. You got the information you requested, so you hang up. In programming terms, this would be an example of synchronous code (sometimes thought of as "normal" code in Node.js).

让自己回到同样的情况.但是,这次您打电话给朋友时,他们很忙.您不想打扰他们,所以请他们稍后打电话给您.您挂断电话,但是现在等待.一个小时后,他们给您回电并告诉您时间.这是异步代码的思考过程.

Put yourself back in the same situation. However, when you call your friend this time, they're very busy. You don't want to bother them so you ask them to call you later. You hang up, but now you wait. An hour later, they call you back and tell you the time. This is the thought process of asynchronous code.

屏幕后面还有很多事情,但是为了简单起见,我不会用所有这些信息轰炸您.

There's a lot more that goes on behind the screen, but for simplicity's sake, I'm not going to bombard you with all that information.

Promise对象表示异步操作的最终完成(或失败)及其结果值.

The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

https://developer. mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise

让我们分解代码以更好地理解问题.

Let's break the code down to better understand the problem.

  • User.send()返回一个承诺.
  • Promise.then() 返回一个承诺.
  • User.send() returns a Promise.
  • Promise.then() also returns a Promise.

因此,您的代码确实看起来像这样:

Therefore, your code really looks like this:

var messageSent = Promise --> Promise

A Promise处于以下状态之一:

A Promise is in one of these states:

  • 待审核:初始状态,既未实现,也未拒绝.
  • 已完成:表示该操作已成功完成.
  • 已拒绝:表示操作失败.
  • pending: initial state, neither fulfilled nor rejected.
  • fulfilled: meaning that the operation completed successfully.
  • rejected: meaning that the operation failed.

https://developer. mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise

我对messageSent对象做了一个console.log,我得到了这个Promise { <pending> }

I did a console.log to the messageSent object and I got this Promise { <pending> }

尽管您将变量定义为Promise,但它尚未立即完成,因此尚未返回任何值.它处于待处理状态.

Although you defined the variable as a Promise, it isn't completed right away, and therefore no value is returned yet. It's in its pending state.

那么,我们如何检索Promise的结果?我们必须等待.

So, how do we retrieve the result of a Promise? We have to wait for it.

  • 保持简单的流程,您可以使用await关键字.它所做的只是在继续执行其他代码之前,等待Promise被兑现或拒绝.考虑以下示例:

  • Keeping a simple flow, you can use the await keyword. All it does is wait for the Promise to be fulfilled or rejected before continuing the execution of further code. Consider the following example:

// Asynchronous context (meaning within an async function) needed to use 'await.'

var messageSent = await user.send(embed);

await messageSent.react('✅');
await messageSent.react('❎');

// Create reaction collector.

  • 或者,您可以坚持使用then()链.在实现Promise后,将使用返回的值调用该回调.在某些情况下,这很简单.但是,回调会很快变得混乱,并且返回值的范围将受到限制.考虑以下示例:

  • Alternatively, you could stick to then() chains. The callback will be called with the returned value upon the fulfillment of the Promise. In some contexts, this is simple. However, callbacks can get messy very quickly, and the scope of the returned values will be limited. Consider this example:

    user.send(embed)
      .then(messageSent => {
        messageSent.react('✅')
          .then(() => messageSent.react('❎'))
            .then(() => {
              // Create reaction collector.
            });
      });
    
    // Keep in mind that the code here will be executed immediately after 'user.send(embed).'
    

  • 我可能已修复它,由于某种原因它没有返回消息的对象,所以我在.then

    I might have fixed it, for some reason it wasn't returning the object of the message so I added messageSent = message; to the .then

    这适用于您的情况,因为then()回调中的值将是已实现的Promise,并且您正在将变量设置为返回的值.不过,这不是最好的主意.

    This works in your case because the value in the then() callback will be the fulfilled Promise, and you're setting the variable to the returned value. This isn't the best idea, though.

    如果Promise被拒绝,则意味着出了点问题.必须捕获源自拒绝的承诺的错误.如果不是,您将在控制台中收到一条警告,提示错误.

    When a Promise is rejected, it means something went wrong. Errors originating from rejected Promises must be caught. If they aren't, you'll receive a warning in the console with the error.

    • 您可以附加catch()方法,该方法的作用与then()类似,除了将错误作为其回调参数返回并且仅在拒绝时才调用.考虑以下简短示例:

    • You can attach catch() methods which will work similarly to then(), except returning the error as its callback parameter and only being called upon rejection. Consider this short example:

    user.send(embed)
      .then(messageSent => {...})
      .catch(console.error);
    

  • 您可以使用try...catch语句来代替附加多个catch()方法.如果try块内的任何Promises被拒绝,则执行catch块内的代码.例如:

  • Instead of attaching multiple catch() methods, you can use a try...catch statement. If any Promises inside of the try block are rejected, the code inside the catch block is executed. For example:

    try {
      const user = await bot.fetchUser('someID');
      await user.send(embed);
    } catch(err) {
      console.error(err);
    }
    

    • Discord.js Documentation
    • MDN Documentation

    这篇关于如何正确地执行createReactionCollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆