javascript - 无法解析 Promise 对象
问题描述
我正在使用链接Fetch
来获取与文章相关的图像。首先,我获取文章的标题,然后将它们传递给以Unsplash API
获取相关图像。
问题是我不能得到我的结果,object
而只能作为promise
. 我想用从内部返回的对象填充div
“结果” 。我也使用过,但没有帮助,仍然是相同的结果。id
async function
cards
variable
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()
};
注意:我使用了有关堆栈溢出的教程和答案,但这些都没有帮助。
解决方案
不会像您想象的那样等待您映射的承诺。尝试Promise.all代替:
const cards = await Promise.all(program.results.map(async result => {
const response = await fetch(url2 + result.title);
return response.json();
}));
推荐阅读
- python - 聚类数据的散点图,以显示聚类和中心
- python - 遍历 python 数组并找到 50 个值的均值/最小值/最大值
- git - Git - 如何在新的发布标签/版本下绑定多个 MR 的更改?
- python - PyInstaller,使模块像普通 Python 一样不可导入
- spring - SpringBoot2运行时如何加载新添加的资源
- javascript - 如何使用可变 URL 进行重定向
- ruby - ruby中的文件删除
- bash - 在 zenity 对话框上按 no 或 cancel 退出脚本
- java - Openshift OOM Killer 使用哪种内存指标
- php - php oop(__construct) 文件上传