javascript - 从 fetch 中获取字符串?

标签 javascript node.js discord.js

我想知道如何从这次获取中获取字符串。到目前为止我有这段代码,例如,我想要像

这样的级别
message.reply(`Your level is ${level}`)

现在我有这个代码:

if(args[0]) {
  let krunkerName = args[0]
  const api = `https://apiktracer.herokuapp.com/user/${krunkerName}`;

  fetch(api)
    .then(res => res.text())
    .then(body => console.log(body));

  message.channel.send() //String here

} else {
  message.reply("Please select a user to check stats on")
}

console.log 中,当我输入名称时,我立即得到此信息,在此示例中 mackex5x5:

{"stats":{"name":"mackex5x5","id":2858585,"score":2921985,"level":51,"levelProgress":28,"kills":25913,"deaths":5309,"kdr":"4.88","kpg":"19.92","spk":"112.76","totalGamesPlayed":1301,"wins":922,"loses":379,"wl":"0.71","playTime":"3d 26m","funds":22280,"clan":false,"featured":"No","hacker":false,"following":0,"followers":3,"shots":186973,"hits":72936,"nukes":71,"meleeKills":59,"createdDate":"2019-04-13","createdTime":"13:06:00","lastPlayedClass":"Marksman"},"uuid":"3e78ef6b-6121-42db-a112-e6757e5d0bf4","error":"False"}

最佳答案

您希望 .send.reply 位于您的 .then 链中。

if(args[0]) {
  let krunkerName = args[0]
  const api = `https://apiktracer.herokuapp.com/user/${krunkerName}`;

  fetch(api)
  .then(res => res.json())
  .then(body => {
       console.log(body)
       message.reply(`Your level is ${body.stats.level}`) //String here
  });

}else{
  message.reply("Please select a user to check stats on")
}

因为 fetch api 是异步调用,因此会在将来解析,所以 message.channel.sendmessage.reply在解析之前被调用。

关于javascript - 从 fetch 中获取字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59440595/

相关文章:

node.js - 我可以在 Node 项目中使用 Nuget 包吗?

node.js - 无法在 Centos 服务器上安装 bcrypt node.js 模块

javascript - React Infinite Scroll 超出最大更新深度

javascript - 根据参数将消息发送到特定 channel

discord.js - Discord js创建不和谐类别

javascript - 如何将javascript文件导入qml worker脚本

javascript - Angular 2 中的 UX 效果

javascript - 如何阻止 "iframe"显示以前加载的(旧)内容?

javascript - Discord.js ".addRole"问题

javascript - 向图像添加字段(输入)