From 4f238222647aef1220e217546889bc9d664904e2 Mon Sep 17 00:00:00 2001 From: SpaceEEC Date: Fri, 23 Jun 2017 21:49:56 +0200 Subject: [PATCH] Wait for the websocket event when creating a guild (#1524) * Wait for the websocket event when creating a guild * using TOOK_TOO_LONG error * resolve after timeout with an unavailable guild object --- src/structures/ClientUser.js | 25 ++++++++++++++++++++++--- src/structures/Guild.js | 2 +- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/src/structures/ClientUser.js b/src/structures/ClientUser.js index beb624623..cd04ad8f3 100644 --- a/src/structures/ClientUser.js +++ b/src/structures/ClientUser.js @@ -298,11 +298,30 @@ class ClientUser extends User { */ createGuild(name, { region, icon = null } = {}) { if (!icon || (typeof icon === 'string' && icon.startsWith('data:'))) { - return this.client.api.guilds.post({ data: { name, region, icon } }) - .then(data => this.client.dataManager.newGuild(data)); + return new Promise((resolve, reject) => + this.client.api.guilds.post({ data: { name, region, icon } }) + .then(data => { + if (this.client.guilds.has(data.id)) return resolve(this.client.guilds.get(data.id)); + + const handleGuild = guild => { + if (guild.id === data.id) { + this.client.removeListener(Constants.Events.GUILD_CREATE, handleGuild); + this.client.clearTimeout(timeout); + resolve(guild); + } + }; + this.client.on(Constants.Events.GUILD_CREATE, handleGuild); + + const timeout = this.client.setTimeout(() => { + this.client.removeListener(Constants.Events.GUILD_CREATE, handleGuild); + resolve(this.client.dataManager.newGuild(data)); + }, 10000); + return undefined; + }, reject) + ); } else { return this.client.resolver.resolveBuffer(icon) - .then(data => this.createGuild(name, region, this.client.resolver.resolveBase64(data) || null)); + .then(data => this.createGuild(name, { region, icon: this.client.resolver.resolveBase64(data) || null })); } } diff --git a/src/structures/Guild.js b/src/structures/Guild.js index e9abbda85..84ab909b2 100644 --- a/src/structures/Guild.js +++ b/src/structures/Guild.js @@ -68,8 +68,8 @@ class Guild { */ this.id = data.id; } else { - this.available = true; this.setup(data); + if (!data.channels) this.available = false; } }