简体   繁体   中英

Can't resolve Promise object

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();
}));

Since within your map() you are again using an async function. Note that Async-Functions always returns promise. So you need to handle promise outside using then() catch() block

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; // Here a promise is returned
    });

  cards.then(data=>{
     console.log(data);// Here you can get the data
      this.cards = data; 
  }).catch(()=>{
     console.log("Error"); 
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM