为了账号安全,请及时绑定邮箱和手机立即绑定

如何获取多个 API 请求或 URL 并从每个 URL 或 API 请求中检索数据?

如何获取多个 API 请求或 URL 并从每个 URL 或 API 请求中检索数据?

胡说叔叔 2023-07-06 15:18:40
在此方法中,我获取了单个 API 请求 URLfunction fetchData() {  let url = 'http://127.0.0.1:8000/api/onlineUserData';  fetch(url)    .then(response => response.json())    .then(data => {      var users=data.users;      console.log(data.users);    });}当我这样做时console.log(data.users)。结果或者数据会是这样的。[["Month", "Anam", "Panam", "duliyan"], ["Apr-16", 21, 26, 29], ["May-07", 0, 0, 5]] 但现在我想获取多个 URL 或 API 请求,并同时检索每个 API 请求数据。从此链接中我找到了 Promise 的用途,但我不知道如何使用检索单个 API 请求数据 如何同时获取多个 API 请求或 URL?function fetchData() {  let urls = [    'http://127.0.0.1:8000/api/onlineUserData',    'http://127.0.0.1:8000/api/offlineUserData'  ]  let requests = urls.map(url => fetch(url));  Promise.all(requests)    .then(responses => responses.forEach(      response => console.log(`${response.url}: ${response.status}`)    ));}
查看完整描述

1 回答

?
交互式爱情

TA贡献1712条经验 获得超3个赞

将您的代码更新为以下内容:


function fetchData(){

    let urls = [

     {

        url: 'http://127.0.0.1:8000/api/onlineUserData',

        type: 'offline'

     },

     {

        url: 'http://127.0.0.1:8000/api/offlineUserData',

        type: 'offline'

     },

     {

        url: 'http://127.0.0.1:8000/api/onlineUserData',

        type: 'online'

     },

    ];



    let requests = urls.map(item => fetch(item.url).then(response => response.json()));


    const resultData = { offline: [], online: [] };


    Promise.all(requests)

     .then(datas => {

       datas.forEach(

        (data, i) => {

         const url = urls[i];

         if (url.type === 'offline') 

             resultData.offine.push({...url, data});

         if (url.type === 'online') 

             resultData.online.push({...url, data});

        });


        console.log({resultData});

        /*

          {

             resultData: {

                offline: [

                  {

                    url: 'http://127.0.0.1:8000/api/oflineUserData',

                    type: 'offline',

                    data: [...]

                  },

                  {

                    url: 'http://127.0.0.1:8000/api/offlineUserData',

                    type: 'offline',

                    data: [...]

                  },

                ],

                online: [

                  {

                    url: 'http://127.0.0.1:8000/api/onlineUserData',

                    type: 'online',

                    data: [...]

                  },

                ]

             }

           }

        */

       }

  ));

}


查看完整回答
反对 回复 2023-07-06
  • 1 回答
  • 0 关注
  • 124 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信