How can functions be used to asynchronously fetch information to later re-use in another function?
The following code shows what is happening. I have a function getInfo which in turn uses getDependencies to fetch some information.
In the function itself the data is returned successfully. But when I want to use that in the other function, it shows an array of Promises.
const request = async function(url) {
return fetch(url)
.then(res => res.json())
.catch(err => { console.warn(err) });
};
const getDependencies = async function(items) {
return items.map(async (item) => {
await request(item.url).then((res) => {
console.log('res: ', res);
// it successfully logs the response here...
// res: { name: 'myObject' }
// this happens 5 times
// I would like to adjust the object for
// each item it wil return
return { name: item.name, res };
});
});
}
const getInfo = async function(details) {
return details.map(async (detail) => {
const result = await getDependencies(detail.items);
// but here it is showing that there are 5 promises instead of the results
console.log(result)
// result: (5) [Promise, Promise, Promise, Promise, Promise]
});
}