Sorry for my bad English. But i'm stuggling with an problem and I hope someone can help me out.
const FinalResult = [];
const users = [
{
short: "gurdt",
gameTag: "gurdt#3199278"
},
{
short: "lc",
gameTag: "LC_92#4607792"
},
{
short: "ray",
gameTag: "The_Green_Ray"
},
{
short: "leon",
gameTag: "Theaxeman777#7613572"
}
];
async function getData(user) {
const config = {
method: "get",
url: `https://my.callofduty.com/api/papi-client/stats/cod/v1/title/mw/platform/uno/gamer/${encodeURIComponent(
user
)}/profile/type/wz`,
headers: {
Cookie:
"TOKEN-1234"
}
};
const rawResponse = await axios(config);
const result = {
user: user,
...rawResponse.data.data.weekly.all.properties
};
return result;
}
users.map((user) => {
const data = getData(user.gameTag);
FinalResult.push(data);
return false;
});
console.log(FinalResult);
What I want is that he loops over the users
and make here one big array of all the results FinalResult
.
Hope that you know what I mean, otherwise tomorrow I will update this question as I'm on my computer and put more info..
CodePudding user response:
Map each users
entry to a promise that resolves with the data you want. Pass this array of promises to Promise.all()
to create a single promise you can await.
// this will make for cleaner code
const gamerApi = axios.create({
baseURL:
"https://my.callofduty.com/api/papi-client/stats/cod/v1/title/mw/platform/uno/gamer/",
headers: {
Cookie: "TOKEN-1234;",
},
});
const promises = users.map(async (user) => {
const { data } = await gamerApi.get(
`${encodeURIComponent(user.gameTag)}/profile/type/wz`
);
return {
user,
...data.data.weekly.all.properties,
};
});
// If you're currently in an async function...
const finalResult = await Promise.all(promises);
// otherwise, use .then()...
Promise.all(promises).then((finalResult) => {
// use finalResult here
});
The result will be an array of objects with a user
property merged with whatever is in the response.