繁体   English   中英

无法解析 Promise object

[英]Can't resolve Promise object

我正在使用链式Fetch来获取与文章相关的图像。 首先,我获取文章的标题,然后将它们传递给Unsplash API以获取相关图像。

问题是我无法获得object的结果,而只能获得promise的结果。 我想用 object 填充带有“结果” iddiv ,我从cards variable中的async function返回。 我也使用了Timeout但没有帮助,仍然是相同的结果。

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

注意:我使用了有关 Stack overflow 的教程和答案,但这些都没有帮助。

您映射的承诺不会像您想象的那样等待。 改为尝试Promise.all

const cards = await Promise.all(program.results.map(async result => {
    const response = await fetch(url2 + result.title);
    return response.json();
}));

由于在您的map()中,您再次使用async function。 Note that Async-Functions always returns promise.因此,您需要使用then() catch()块在外部处理 promise

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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