Reputation: 152
I want to call an async function making an API call inside another function.
Specifically in the code below I am defining an asynchronous function verifyEmail
making an API call to a verification service for mail adresses. The function is working when I test it with a random email.
I would like to be able to call this function inside the getProfileInfos
function that parses a json file and return an array of objects. The verifyEmail(result.dropcontact.email)
is wrong since it will always return the non-resolved Promise
. I did some research but do not find the right syntax to call the async function and wait for the result to set the email in my object.
Any help is appreciated!
const verifyEmail = async (email) => {
const response = await fetch(`https://apilayer.net/api/check?access_key=******&email=${email}`);
const data = await response.json();
if (data.format_valid && data.score > 0.5) {
return data.email;
};
}
const getProfileInfos = (data) => {
const jsonData = JSON.parse(data);
const results = jsonData.map((result) => {
if (result.general) {
const firstName = result.general.firstName;
const lastName = result.general.lastName;
const company = result.jobs[0].companyName;
const jobTitle = result.jobs[0].jobTitle;
const email = result.dropcontact ? verifyEmail(result.dropcontact.email) : undefined;
return {
firstName,
lastName,
company,
jobTitle,
email
}
}
});
return results;
}
Upvotes: 2
Views: 3207
Reputation: 1995
Try to define async inside the getProfileInfos
props and invoke await before verifyEmail
e.g.
const getProfileInfos = async (data) => {
const jsonData = JSON.parse(data);
const results = jsonData.map((result) => {
if (result.general) {
const firstName = result.general.firstName;
const lastName = result.general.lastName;
const company = result.jobs[0].companyName;
const jobTitle = result.jobs[0].jobTitle;
const email = result.dropcontact ? await verifyEmail(result.dropcontact.email) : undefined;
return {
firstName,
lastName,
company,
jobTitle,
email
}
}
});
return results;
}
Upvotes: 1
Reputation: 92367
Add async
keyword to getProfileInfos
and change line const email = ...
to
const email = result.dropcontact ? (await verifyEmail(result.dropcontact.email)) : undefined;
Upvotes: 1