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
JavaScript
x
23
23
1
function repeatsChecker() {
2
let api_data_values = []
3
4
fetchData().then(data => {
5
for (let i = 0; i < data.length; i++) {
6
api_data_values.push(data[i].name)
7
}
8
})
9
10
return api_data_values
11
12
}
13
14
// testing for similarities
15
16
async function test() {
17
let name = "Joe"
18
let test = await repeatsChecker();
19
console.log(test[0])
20
}
21
22
test()
23
When I compile a simple if statement everything returns true and when I do console.log(test[0]) it returns undefined?
Advertisement
Answer
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:
JavaScript
1
6
1
function repeatsChecker() {
2
return fetchData().then(data => {
3
return data.map(value => value.name);
4
});
5
}
6
Or with async/await:
JavaScript
1
5
1
async function repeatsChecker() {
2
const data = await fetchData();
3
return data.map(value => value.name);
4
}
5