[英]Can't resolve Promise object
我正在使用鏈式Fetch
來獲取與文章相關的圖像。 首先,我獲取文章的標題,然后將它們傳遞給Unsplash API
以獲取相關圖像。
問題是我無法獲得object
的結果,而只能獲得promise
的結果。 我想用 object 填充帶有“結果” id
的div
,我從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.