I Have 2 functions one which uses async and await to grab data and place it into an array. The second is acts like a checker to see if the user inputs a similar value as seen on the database
function repeatsChecker() {
let api_data_values = []
fetchData().then(data => {
for (let i = 0; i < data.length; i ) {
api_data_values.push(data[i].name)
}
})
return api_data_values
}
// testing for similarities
async function test() {
let name = "Joe"
let test = await repeatsChecker();
console.log(test[0])
}
test()
When I compile a simple if statement everything returns true and when I do console.log(test[0]) it returns undefined?
CodePudding user response:
repeatChecker
isn't returning a promise, so the fact that you're await
ing doesn't have any meaningful effect. console.log(test[0])
executes before api_data_values.push(data[i].name)
.
Try this:
function repeatsChecker() {
return fetchData().then(data => {
return data.map(value => value.name);
});
}
Or with async/await:
async function repeatsChecker() {
const data = await fetchData();
return data.map(value => value.name);
}