简体   繁体   English

如何向此函数添加异步等待

[英]How can I add async await to this function

export function fetchNews(data) {
    const news = []

    var numOfArticlesArray = fetchNewsPreprocessing(data)

    data.map((interest, index) => {

        fetch(`https://newsapi.org/v2/top-headlines?country=us&category=${interest}&apiKey=`)
        .then(res => res.json())
        .then(res => res.articles)
        .then(res => {
            
            for (let i = 0; i < numOfArticlesArray[index]; i++) {
                news.push(res[i])
            }
        })
        .catch(err => console.log(err))
        
    })

    console.log(news);

}

So here is the function, my issue is that I'm getting this console.log(news);所以这是函数,我的问题是我得到了这个console.log(news); before I finish appending to my news array in here news.push(res[i]) which results in a blank array.在我完成将这里的news.push(res[i])添加到我的news数组之前,这会导致一个空白数组。

I tried adding async and await to the function like this async function fetchNews(data) and await data.map((interest, index) => { but no use.我尝试将 async 和 await 添加到这样的async function fetchNews(data)await data.map((interest, index) => {但没有用。

thanks in advance.提前致谢。

Do you want to execute your fetch() calls serially, or in parallel?您想串行还是并行执行fetch()调用?

If you want to execute them serially then something like this will work:如果你想串行执行它们,那么这样的事情将起作用:

export function fetchNews(data) {
  const news               = [];
  const numOfArticlesArray = fetchNewsPreprocessing(data);
  
  data.map( async (interest, index) => {
    const url = `https://newsapi.org/v2/top-headlines?country=us&category=${interest}&apiKey=`;
    
    try {
      const res = await fetch(url).then(res => res.json());
      const articles = res.articles;
     
      for ( let i = 0 ; i < numOfArticlesArray[index] ; i++ ) {
        news.push(articles[i]);
      }
    
    } catch (err) {
      console.log(err);
    }
        
  })

  console.log(news);

}

If you want to execute them in parallel, however, then something like this is what you want:但是,如果您想并行执行它们,那么您想要的是这样的:

export async function fetchNews(data) {
  const news               = [];
  const numOfArticlesArray = fetchNewsPreprocessing(data);
  const requests           = data.map( (interest, index) => {
    const url = `https://newsapi.org/v2/top-headlines?country=us&category=${interest}&apiKey=`;
    const res = fetch(url).then(res => res.json());
    
    return res;
  })
  const responses = await Promise.all( requests );

  for ( const i = 0 ; i < responses.length ; ++i ) {
    const res = responses[i];
    const articles = res.articles;
    
    for ( let j = 0 ; j < numOfArticlesArray[i] ; ++j ) {
      news.push(articles[j]);
    }

  }

  console.log(news);

}

You should put await in front of fetch() instead.你应该把await放在fetch()前面。 For example, this piece of code will output the news array with the test element:例如,这段代码将输出带有test元素的news数组:

async function fetchNews(data) {
  let news = [];
  await fetch(url).then(() => news.push('test'));
  console.log(news)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM