首页 > 解决方案 > 无法解析 Promise 对象

问题描述

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

问题是我不能得到我的结果,object而只能作为promise. 我想用从内部返回的对象填充div“结果” 。我也使用过,但没有帮助,仍然是相同的结果。idasync functioncards variableTimeout

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

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

标签: javascriptasync-awaitfetch

解决方案


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

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

推荐阅读