Javascript 链式获取立即获得第一个结果
我正在发送链式Javascript 链式获取立即获得第一个结果,javascript,async-await,fetch-api,Javascript,Async Await,Fetch Api,我正在发送链式Fetch请求。首先,我从数据库中检索数据并请求与我得到的每个标题相关的图片 在发送图像请求之前,HTML代码不会加载到结果div。所以看文章要花很长时间。如何在图像请求开始发送之前加载文本 async function getArticles(params) { url = 'http://127.0.0.1:8000/articles/api/?' url2 = 'https://api.unsplash.com/search/photos?client_id=
Fetch
请求。首先,我从数据库中检索数据并请求与我得到的每个标题相关的图片
在发送图像请求之前,HTML
代码不会加载到结果div
。所以看文章要花很长时间。如何在图像请求开始发送之前加载文本
async function getArticles(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 article = await fetch(url + params).then(response => response.json());
const cards = await Promise.all(article.results.map(async result => {
try {
let image = await fetch(url2 + result.title).then(response => response.json())
let card = // Creating HTML code by using database info and Splash images
return card
} catch {
let card = // Creating HTML code by using info and fallback images from database
return card
}
}))
document.getElementById('results').innerHTML = cards.join("")
};
我尝试分别使用它们,但得到的是Promise对象。如果您不想等待所有回迁,请使用普通的for
循环,然后依次等待每个回迁
异步函数getArticles(params){
url='1〕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-article=wait-fetch(url+params)。然后(response=>response.json());
for(设i=0;iresponse.json())
card=//使用数据库信息和Splash图像创建HTML代码
}抓住{
card=//使用数据库中的信息和回退图像创建HTML代码
}
document.getElementById('results').innerHTML+=card;
}
}
不要使用等待所有问题解决的Promise.all()
。使用for
循环,该循环执行等待获取
,并按顺序将该响应添加到DOM。@Barmar谢谢,您可以添加代码吗?我不知道在哪里使用这个循环以及如何使用。因为我已经在映射第一次获取的结果