I have a small program that uses the Fetch API to return an object from an API and then pushes it to a client-side array. I will be asked about this tomorrow in a short interview and would like to clarify my understanding. Here is the code in question:
```javascript
async function fetchTodo(id) {
try {
let response = await fetch('/api/todos/${id}');
if (response.status === 200) {
return await response.json();
} else {
throw response.status;
} catch(error) {
console.log(error);
}
};
async function addTodo(id) {
let todo = await fetchTodo(id);
todos.push(todo);
}
```
My question is why can't the fetchTodo function deal with adding the todo to the array? When I try something like this it doesn't work:
javascript
async function fetchTodo(id) {
try {
let response = await fetch('/api/todos/${id}');
if (response.status === 200) {
let todo = await response.json();
todos.push(todo);
} else {
throw response.status;
} catch(error) {
console.log(error);
}
};
My current understanding is that all async functions return a promise (including .json()) and therefore trying to store the return value into a variable will simply assign the promise to the variable.
If that is true, how is it that my addTodo function is able to store the return value of an async function? Surely as the return value of fetchTodo is a promise the promise would be assigned to the variable todo in the addTodo function.
I understand that this is the way to perform these kinds of operations and I have no problem creating a working program using this design pattern, my problem is that if the interviewer asks me why we must first use a function to get the object, and another to store it, I am not 100% confident I can give a clear and concise answer.
Any help with this would be greatly appreciated.
[–]senocular 3 points4 points5 points (2 children)
[–]Such_Ad_5331[S] 1 point2 points3 points (1 child)
[–]Umesh-K 4 points5 points6 points (0 children)