I am trying to understand promises but I am finding myself in a loop of using await and async over and over again.
My understanding is that async keyword added before the function, you can indicate that the function always returns a promise.
I have a function that reads a file and returns a promise, the name is getDataFromFile();
I want to be able to get the data from it once it resolves, so rather than using resolve, reject new promise I want to use await async.
After await when the promise is returned I want to get the data and assign it to DataFromPromise variable.
let DatafromPromise = {};
const loadDataPromise = async () => { // Since its async, it seems like its returning a promise too
try {
const myPromise = getDataFromFile();
DatafromPromise = (await myPromise).value;
//console.log(DatafromPromise); // This has value
} catch (error) {
console.log(error);
}
};
loadDataPromise();
console.log(DatafromPromise); // This is empty? Why?
If I put await loadDataPromise() I will have to put async around this entire block of code too, now see that is putting me in a loop of await/async.
getDataFromFile is already returning a promise. Then I add const loadDataPromise which is a const function returning a promise.. Then if I add await loadDataPromise, I feel like I am going in a loop of returning promises without actually getting the data.
At what point in the code the promise is getting resolved and value is assigned?
Thanks so much for helping.