In my code, I want to create a user (partner) and then after the post request has finished completely, get all the partners from an api (including the one just created) then access the Id of that partner to use in the rest of my code.
*PartnerName is also equal to whatever the user puts inside the form that posts here
await axios
.post(newPartnerUrl, { Name: PartnerName }, options)
.then(async () => {
const partnersRes = await axios.get(getPartnersUrl, options);
const partners: IPartner[] = partnersRes.data;
partners.map((partner: IPartner) => {
if (partner.Name === PartnerName) {
partnerId = partner.Id
}
});
});
const PartnerId = partnerId
This is the code, if you could help make it work and/or more efficient that would be much appreciated :)
CodePudding user response:
I'd suggest that you should fully use async/await
instead of mixing it with then
. After that, you can use find
to get the latest partner according to PartnerName
.
async function addPartner() {
await axios.post(newPartnerUrl, { Name: PartnerName }, options);
const partnersRes = await axios.get(getPartnersUrl, options);
const partners: IPartner[] = partnersRes.data;
//find the newly added partner
const newPartner = partners.find((partner: IPartner) => partner.Name === PartnerName);
const PartnerId = newPartner.id
//TODO: You can do something else with the newly added partner
}
CodePudding user response:
Found a workaround, turns out the partner wasn't being added to the database at the time of the get request so I've added a timeout for 2 seconds which allows the partner time to be added.
for anyone with this issue as well here is the code
function delay(n){
return new Promise(function(resolve){
setTimeout(resolve,n*1000);
});
}