【问题标题】:Multiple JS api calls多个 JS api 调用
【发布时间】:2018-04-02 17:26:33
【问题描述】:

我需要让所有用户都有一个特定的 API url(例如:https://example.com/api/userType/1/)和他们的特定数据,该数据存储所有用户的数组及其唯一的 API url,例如

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

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

【问题讨论】:

    标签: javascript api


    【解决方案1】:
      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()));
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-07
      • 1970-01-01
      • 2019-07-26
      • 2020-10-24
      • 2020-11-05
      • 1970-01-01
      • 2021-02-02
      • 1970-01-01
      相关资源
      最近更新 更多