i am having confusion about the state of the promise after using await keywordhere's the code with the correct data`
async function myFunc(){ try{ const response=await fetch("https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json" ) if(!(response.ok)){ throw new error(`HTTP Error ${response.status}`); } const data=await response.json(); console.log(data[9].name); } catch(error){ console.error(`could not get products: ${error}`); } finally{ console.log("THANK YOU !!!!"); }}myFunc();
This correctly outpus the data[9], but if i use the return data statement after this it doesnt work , heres the relevant code
async function fetchProducts() { try { const response = await fetch("https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json", ); if (!response.ok) { throw new Error(`HTTP error: ${response.status}`); } const data = await response.json(); return data; } catch (error) { console.error(`Could not get products: ${error}`); }}const promise = fetchProducts();console.log(promise[0].name); // "promise" is a Promise object, so this will not work
But if i use this at the end , it works
const promise = fetchProducts();promise.then((data) => console.log(data[0].name));
my confusion is if the await keyword at the beginning is there to resolve the promise then why do we have to again use (.then) outside the function to wait for the promise to resolve
I tried using chatgpt for the answers but didn't get a satisfactory explanation , also i have been using mdn web docs and the code is an example on the website , here's the link to the artcie .
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Promises