简体   繁体   English

异步 Function 返回 promise

[英]Async Function returns promise

I have a function that returns the guilds prefix in Discord.JS:我有一个 function 返回 Discord.JS 中的公会前缀:

getprefix.js:获取前缀.js:

const GuildSchema = require("../Database/Models/GuildConfigs");
const { DEFAULT } = require("./config");

const getprefix = async (id) => {
  const guildConfigs = await GuildSchema.findOne({
    GuildID: id,
  });

  let PREFIX = DEFAULT;

  if (guildConfigs && guildConfigs?.Prefix) {
    PREFIX = guildConfigs?.Prefix;
  }
};

module.exports = { getprefix };

I call the function in another file using this:我使用这个在另一个文件中调用 function:

let prefix = getprefix(message.guild.id);

prefix.then(() => {
    console.log(prefix);
});

The problem is it returns this in the console:问题是它在控制台中返回:

Promise { '!' }

Is it possible to just return the actual prefix that is inside the quotes with out the Promise?是否可以只返回引号内的实际前缀而没有 Promise?

Yes, but you must return the value from the async function.可以,但您必须从异步 function 返回值。

getprefix.js:获取前缀.js:

const GuildSchema = require("../Database/Models/GuildConfigs");
const { DEFAULT } = require("./config");

const getprefix = async (id) => {
  const guildConfigs = await GuildSchema.findOne({
    GuildID: id,
  });

  let PREFIX = DEFAULT;

  if (guildConfigs && guildConfigs?.Prefix) {
    PREFIX = guildConfigs?.Prefix;
  }
  return PREFIX;
};

module.exports = { getprefix };

and change the call:并更改呼叫:

let prefix = getprefix(message.guild.id);

prefix.then((value) => {
    console.log(value);
});

First you must return a value from your async function called getprefix .首先,您必须从名为getprefix的异步 function 返回一个值。 Secondly you must console.log the result of the promise returned by getprefix function instead of the promise itself:其次,您必须console.log记录 getprefix function 而不是 promise 本身返回的getprefix的结果:

const getprefix = async (id) => {
  const guildConfigs = await GuildSchema.findOne({GuildID: id});
  
  if (!guildConfigs || !guildConfigs.Prefix) {
    return DEFAULT;
  }

  return guildConfigs.Prefix;
};

getprefix(message.guild.id).then(prefix => console.log(prefix));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM