I'm trying to get all users from api and I need to find the user which most get paid.
so for example
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))
so my plan is users[0],users[1] something like a make function which I add index number via loop.
and get all users and find out who get the most paid.
so my question is how can do fetch users step by step.
You can use Array reduce to get the user who less payed and combine with Promise.all using async / await to fetch all user data
'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();
Maybe try something like this? Do you need to use async
?
Basically, the strategy is this:
$.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'
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.