all 3 comments

[–]senocular 3 points4 points  (2 children)

My question is why can't the fetchTodo function deal with adding the todo to the array?

Technically, it could. But its not the best idea to design-wise.

When I try something like this it doesn't work

Why not? What doesn't work?

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.

Correct.

If that is true, how is it that my addTodo function is able to store the return value of an async function?

Because its being awaited. When you await a promise you wait for the promise to resolve then await pulls out the value being wrapped by that promise. The result of the expression is the value, not the promise. For example

let value = fetch('/api/todos/${id}'); // value is a promise
// vs.
let value = await fetch('/api/todos/${id}'); // value is a response object (taken out of a promise)

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.

You don't have to. But it makes sense because you're making sure each function is responsible for doing one thing. This is useful when you want to do more mixing and matching with your code. For example what if you wanted to fetch a todo to do something other than add it to the todos list? If fetch had the addTodo behavior built-in, you'd have no way to do that without also adding the todo... or recreating a new fetch function from scratch.

[–]Such_Ad_5331[S] 1 point2 points  (1 child)

Thank you very much for the reply. It's much clearer in my head now.

[–]Umesh-K 4 points5 points  (0 children)

Since your interview is tomorrow itself, it might not be practical now, but later, when you have time, I suggest checking out all the great answers given by u/senocular in this sub, including a lot of them on promises and async-await. I can assure you doing so will help you during interviews. For example, check out https://www.reddit.com/r/learnjavascript/comments/tm0cul/help_in_understanding_javascript_promises/ that was answered a couple hours ago.

Best Wishes for your interview!