【问题标题】:Iteration through an array in js遍历js中的数组
【发布时间】:2020-10-11 17:40:46
【问题描述】:
  var webhook_array = webhook_url.split(",");
  console.log(webhook_array);
  function send(item) {
    console.log(item)
    request.open("POST", item);
    request.setRequestHeader('Content-type', 'application/json');
  
    var myEmbed = {
      title: embed_title,
      color: hexToDecimal(hexcolour),
      description: message_content,
      footer: {
        text: "Powered by Yapplex Tools",
        icon_url: avatarurl,
      }
    }
    
    var params = {
      username: webhook_username,
      avatar_url: avatarurl,
      embeds: [ myEmbed ]
    }
    request.send(JSON.stringify(params));
  }
  webhook_array.forEach(send);

  function hexToDecimal(hex) {
    return parseInt(hex.replace("#",""), 16)
  }
}

此代码应通过数组中的每个 webhook 并使用它们发送消息。它将它们打印到控制台,这意味着它们在那里并且可以检测到它们,但只调用了一个 webhook(当使用两个 webhook 进行测试时)

【问题讨论】:

  • 您的意思是您的项目正在“console.log(item)”中打印,但没有发出 http 请求?
  • 是的,正是……
  • 您需要使用async/await 并等待每个http 操作完成,然后再进行下一个操作。通常对于异步等待模式,使用 forEach 并不是一个好主意。取而代之的是,将整个代码包装在一个匿名的 async 函数中,并在每个函数调用上使用 await 并使用 for 循环遍历每个 web_hook。另外,假设request 是一个XHR 对象,您可以考虑使用fetch API,因为您可以在它们上使用await。如果你理解有困难,我也可以写代码。
  • @lanxion 为什么我需要等待一个请求完成才能继续前进?我当然可以同时发送多个请求。
  • 你检查过 JSON.stringify(params) 调用中是否有异常吗?我注意到在您使用 avatarurl 的那一行中有一个多余的逗号。也许这会导致序列化问题并导致 request.send() 失败?

标签: javascript node.js electron discord


【解决方案1】:

有几件事可能会给您带来问题。最值得注意的是,您需要创建一个新的 XMLHttpRequest()。



  var webhook_array = webhook_url.split(",");
  console.log(webhook_array);
  function send(item) {
    console.log(item)

    /** CREATE REQUEST HERE */
    const request = new XMLHttpRequest();
    /** SHOULD WORK NOW */

    request.open("POST", item);
    request.setRequestHeader('Content-type', 'application/json');
  
    // Other code...
    request.send(JSON.stringify(params));
  }
  webhook_array.forEach(send);

您包含的示例还有一些未定义的变量(avatarurlwebhook_username)和一个额外的大括号。确保它们在您的代码中的其他地方:它们可能只是文件的一部分,没有出现在您的问题中。希望这会有所帮助!

【讨论】:

  • 未定义的变量是因为这不是完整的代码,仅足以复制我的问题。这些变量确实有值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-06
  • 2023-03-06
  • 2017-01-21
  • 1970-01-01
  • 1970-01-01
  • 2020-10-11
  • 2019-08-08
相关资源
最近更新 更多