I am using chained Fetch
to get images that is relevant to articles. First, I fetch Articles' titles and then pass these to Unsplash API
to get relevant images.
The problem is I can't get my result as object
but only as a promise
. I want to populate div
with "results" id
with object that I return from async function
inside cards
variable
. I used Timeout
as well but didn't help, still the same result.
async function getPrograms(params) {
url = 'http://127.0.0.1:8000/articles/api/?'
url2 = 'https://api.unsplash.com/search/photos?client_id=XXX&content_filter=high&orientation=landscape&per_page=1&query='
const program = await fetch(url + params).then(response => response.json());
this.program = program;
const cards = await program.results.map(async result => {
// Objects that I need to populate card. Ex. title, description, date updated and etc. And also images below (for testing, only returning images):
let images = await fetch(url2 + result.title).then(response => response.json())
return images
});
this.cards = cards;
const printAddress = async () => {
const a = await cards;
return a
};
document.getElementById('results').innerHTML = printAddress()
};
Note: I used tutorials and answers on Stack overflow but these didn't help.
Your mapped promises won't be awaited as you might think. Try Promise.all instead:
const cards = await Promise.all(program.results.map(async result => {
const response = await fetch(url2 + result.title);
return response.json();
}));