簡體   English   中英

如何使用api來獲取大量用戶?使用異步等待

[英]how can I fetch a lot of users by api??with using async await

我正在嘗試從api獲取所有用戶,我需要找到獲得最多報酬的用戶。

例如

let users=['tom','jenny','smith','Joe']

async function getUsers() { 
  let response = await fetch(`http://something.something?q=${users}`);
  let data = await response.json();
  return data;
}

getUsers().then(data =>console.log(data))

所以我的計划是users [0],users [1]類似make函數,我通過循環添加索引號。

並獲得所有用戶,並找出誰獲得了最高的報酬。

所以我的問題是如何逐步獲取用戶。

您可以使用Array reduce來獲得付費較少的用戶,並與Promise.all結合使用async / await來獲取所有用戶數據

'use strict';

/* mock data for testing purposes
const usersData = [{
  name: 'john doe',
  payed: 10,
}, {
  name: 'john doe01',
  payed: 5,
}, {
  name: 'john doe02',
  payed: 8,
}, {
  name: 'john doe03',
  payed: 20,
}, {
  name: 'john doe04',
  payed: 40,
}, {
  name: 'john doe05',
  payed: 37,
}];
*/

async function getUsers() {
  const usersResponse = await Promise.all(
    usersName.map(userName => fetch(`http://something.something?q=${userName}`))
  );

  return usersResponse.map(userResponse => userResponse.json());
}

async function init() {
  try {
    const usersName = [
      'tom',
      'jenny',
      'smith',
      'Joe',
    ];

    const usersData = await getUsers(usersName);

    const userWhoLessPayed = usersData.reduce((prevUser, currentUser) => {
      if (prevUser.payed > currentUser.payed) {
        return currentUser;
      }

      return prevUser;
    });
    console.log(userWhoLessPayed);
  } catch (e) {
    console.error(e);
  }
}

init();

也許嘗試這樣的事情? 您需要使用async嗎?

基本上,策略是這樣的:

  1. 返回所有用戶。 除非端點有一種過濾方法(通過參數-當前無法確定收入最高的藝術家的某種方式)
  2. 返回后,獲取從端點返回的用戶列表並進行過濾。 下面,我們正在過濾返回的對象數組,以尋找稱為“ pay”的虛擬鍵的最大值。
    $.when( getAllArtists() ).then(function (allArtistResults) {
        $.each(allArtistResults, function(key, value){
             // let's just pretend we get an array of objects back
             // you could just filter it here?
             // props on below: https://stackoverflow.com/questions/4020796/finding-the-max-value-of-an-attribute-in-an-array-of-objects
             Math.max.apply(Math, value.map(function(artists) { return artists.pay; }))
        }
    }
    function getAllArtists() {
        return $.ajax({
            url: 'your-endpoint-here',
            type: 'GET'
        });
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM