gpt4 book ai didi

javascript - 我将如何迭代 awaitMessages 收集器以在循环递增时收集多个输入?

转载 作者:行者123 更新时间:2023-12-04 08:03:21 24 4
gpt4 key购买 nike

我正在尝试创建一个设置命令,用户在其中输入值,然后将这些值保存在 SQL 数据库中。但是,我无法让 awaitMessages 方法在 for 循环中等待。

let input = []; // declare input as empty array
let setupQ = ['Please enter the role ID of admin', 'Please enter the role ID of mod', 'Please enter the ID of your log channel', 'Please enter the ID of your join/leave channel'];
for (i = 0; i < 4; i++) {
message.channel.send(setupQ[i])

const filter = (user) => {
return user.author.id === message.author.id
};

message.channel.awaitMessages(filter, { max: 1, time: 15000, errors: ['time'] })
.then(async collected => {
input[i] = collected.first().content //takes user input and saves it
}).catch(collected => {
message.channel.send(`:x: Setup cancelled - 0 messages were collected in the time limit, please try again`).then(m => m.delete({ timeout: 4000 }));
});
};

目前发生的情况是,机器人会立即输出问题,而无需等待用户回复。我以前让这个命令起作用,但是通过使用 4 个丑陋且缓慢的 awaitMessages 方法。 (更不用说格式化噩梦了)。

谁能看到我必须做些什么才能让它等待?

最佳答案

要等待每条指令执行,请在 async 函数(如 processStuff)中使用 await

这实际上是一种解决方法,通过利用它的异步范式在 JS 中获得一种同步执行(从外观上看)。

在较早的代码中,您的每个 Promise 的创建都不依赖于要完全评估的前一个 Promise。但在这种情况下,我们正在等待 promise 的创建。

let input = []; // declare input as empty array
let setupQ = ['Please enter the role ID of admin', 'Please enter the role ID of mod', 'Please enter the ID of your log channel', 'Please enter the ID of your join/leave channel'];

async function processStuff(){
for (i = 0; i < 4; i++) {
message.channel.send(setupQ[i])

const filter = (user) => {
return user.author.id === message.author.id
};
try{
let collected = await message.channel.awaitMessages(filter, { max: 1, time: 15000, errors: ['time'] });
input[i] = collected.first().content; //takes user input and saves it
}
catch(e)
{
message.channel.send(`:x: Setup cancelled - 0 messages were collected in the time limit, please try again`).then(m => m.delete({ timeout: 4000 }));
}
};
}

processStuff();

从概念上讲,这相当于将所有 4 个 promise 链接在一起(例如 promise.then(...).then(...).then(...)... ) 以便下一个 promise 的创建(在前一个 promise 的 then 回调中)只能在前一个 promise 得到完全评估并返回新 promise 后才能开始。

关于javascript - 我将如何迭代 awaitMessages 收集器以在循环递增时收集多个输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66333763/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com