[英]How would I iterate an awaitMessages collector to collect multiple inputs as the loop increments?
我正在嘗試創建一個設置命令,用戶在其中輸入值,然后將其保存在 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
function 中使用await
,例如processStuff
。
這實際上是一種通過利用它的異步范例在 JS 中獲得一種同步執行(從外觀上看)的解決方法。
在前面的代碼中,創建每個 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.then(...).then(...).then(...)
....),以便創建下一個 promise(內部then
回調前一個)只能在前一個得到充分評估並返回一個新的 promise 后開始。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.