繁体   English   中英

多个JS API调用

[英]Multiple JS api calls

我需要为所有用户提供一个特定的API网址(例如: https://example.com/api/userType/1/ : https://example.com/api/userType/1/ ),并带有其特定数据,该数据存储了所有具有其唯一API网址的所有用户的数组,例如如

{
  name: "Type 1",
  ...
  users: [
   "https://example.com/api/user/1/",
   "https://example.com/api/user/18/",
   "https://example.com/api/user/40/",
   ...
 ]
 ...
}

我想向所有这些用户展示香草JS,特别是fetchData函数。 我认为进行一个API调用,然后遍历该API调用内的所有用户(在then promise函数中)是不明智的-对他们唯一的API url进行另一个API调用。 我当时想创建一个具有两个函数的闭包函数来进行API调用,但是我不确定这样做的最佳实践。 有关如何正确执行此操作的任何建议?

  async function getUsers(){
    const { users } = (await fetch ("https://example.com/api/userType/1/")).json();
    return Promise.all(users.map(user => fetch(user).then(req => req.json()));
 }

暂无
暂无

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

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