https://codesandbox.io/s/asyncawait-axios-practice-c060n
This is a link to a sandbox I have with simple code. Why does it keep returning a promise and not waiting until the it is finished resolving as I put await before the axios call?
It's as if it's just returning the promis and it's done. If I do a console.log inside the function local scope it will return a promise object and if I return the result and do a console.log in global scope, it will return what I'm looking for. The thing is, I thought I didn't have to do it that way and wait for the promise to resolve. I get that asyn returns a promise and axios does too... so what am I missing when dealing with promises resolving promises?
import axios from "axios";
async function GetPosts() {
const result = await axios.get("https://jsonplaceholder.typicode.com/posts");
const data = await result.data;
return data;
}
const response = GetPosts();
console.log(response);
I just want to make sure my fundamental understanding of what's going on is correct.
- I'm importing axios
- I'm declaring an function called GetPosts() that has await before the axios call. (I'm assuming it will pause until it is finished)
- I'm awaiting for the results data
I receive a promise instead of the intended json. Why?
asyncfunction always returns a Promise; that's pretty much the point. From a non-async context, you can writeGetPosts().then(response => console.log(response))awaitfrom inside anotherasyncfunction.await result.data;, usingawaiton the previous line, when declaringresult, ‘pauses’ program execution untilaxios.get()returns a promise, which means the value will subsequently be available to assign to a variable or return. this is a good article onaxios.get()and also shows example withtry/catchblock, as suggested in Dominic’s answer: flaviocopes.com/axios/#get-requests”Async functions always return a promise, whether you use await or not. That promise resolves with whatever the async function returns, or rejects with whatever the async function throws”, see developers.google article