[英]Can't resolve Promise object
I am using chained Fetch
to get images that is relevant to articles.我正在使用链式
Fetch
来获取与文章相关的图像。 First, I fetch Articles' titles and then pass these to Unsplash API
to get relevant images.首先,我获取文章的标题,然后将它们传递给
Unsplash API
以获取相关图像。
The problem is I can't get my result as object
but only as a promise
.问题是我无法获得
object
的结果,而只能获得promise
的结果。 I want to populate div
with "results" id
with object that I return from async function
inside cards
variable
.我想用 object 填充带有“结果”
id
的div
,我从cards
variable
中的async function
返回。 I used Timeout
as well but didn't help, still the same result.我也使用了
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()
};
Note: I used tutorials and answers on Stack overflow but these didn't help.注意:我使用了有关 Stack overflow 的教程和答案,但这些都没有帮助。
Your mapped promises won't be awaited as you might think.您映射的承诺不会像您想象的那样等待。 Try Promise.all instead:
改为尝试Promise.all :
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由于在您的
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.