Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
67 views
in Technique[技术] by (71.8m points)

javascript - Chained Fetch getting first results immediately

I am sending chained Fetch requests. First, I retrieve data from database and request pictures related to every title I got.

The HTML code won't be loaded to results div before image requests are sent. So it takes long time to see articles. How can I make the text to load before image requests starting to be sent?

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("")

};

I have tried using them separately but I was getting Promise Object.

question from:https://stackoverflow.com/questions/65835149/chained-fetch-getting-first-results-immediately

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you don't want to wait for all the fetches, use an ordinary for loop and await each one sequentially.

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

  for (let i = 0; i < article.results.length; i++) {
    let result = article.results[i];
    let card;
    try {
      let image = await fetch(url2 + result.title).then(response => response.json())
      card = // Creating HTML code by using database info and Splash images
    } catch {
      card = // Creating HTML code by using info and fallback images from database
    }
    document.getElementById('results').innerHTML += card;
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...