我的异步await函数在返回值之前没有等待我的函数完成

时间:2019-05-21 05:52:25

标签: reactjs asynchronous fetch

我的问题是,我的最终回报是在所有操作结束之前立即得到打印。如果为this.state,则会打印一个空数组,因为它会立即打印。如果我返回pop,它将在数据加载之前立即打印。

这很烦人,因为我从一开始就在唯一的功能中等待着。我完全不知道我的代码是怎么回事。基本上,让我填补您的空白。 getStuff()给了我一个ID数组。那很好。这就是asyncForEach

async function asyncForEach(array, callback) {
      for (let index = 0; index < array.length; index++) {
        await callback(array[index], index, array);
     }

它基本上异步地运行foreachloop,因为我获取数据并且想要等待每个返回。 fetch会为我获取一些隐藏在data.appnews.newsitems中的文章,对于每篇文章,我都希望将其置于我的状态,并按时间顺序对其进行排序。所有这些作品。在我的渲染中,它将所有内容一一打印,然后慢慢看到每一篇文章都一一载入。这一切都应该做。但是,它一加载就立即返回我的return语句。我在底部的不同时间使用了promise.all和一个异步函数,它们都在我的所有文章加载之前执行。在promise.all中,由于我的状态为空,它返回一个空数组,然后在控制台help中看到,然后我看到文章从加载到屏幕的状态出现。有人可以向我慢慢解释我的代码发生了什么吗?我真的以为await getstuff().then...会暂停所有内容,等待其中的所有内容完成,然后返回this.state

const getNews = async () => {
  await getstuff().then(result => {
    asyncForEach(result, async gameID => { //fetch data for gameID that I have
     await  fetch(`https://ancient-dusk-43980.herokuapp.com/${gameID}/news`)
        .then(res => res.json())
        .then(data => {
          data.appnews.newsitems.forEach(article => { //push each article to the state
            this.setState({
              articles: [...this.state.articles, article]
            });
            this.state.articles = this.state.articles.sort(function(a, b) {
              return b.date - a.date;// sort each article by date
            });
          });
        })
    });
  })
  return this.state; //this is getting printed instantly. I see an empty array in console
};
Promise.all([getNews()]) //ran this at seperate times then my "init"
.then(val => { // both are used to 
  console.log(val)//
})
async function init () {
  await getNews()
  console.log('help')
}
init()

理想情况下,在我的console.log('help') or my console.log(val)I want to replace those with more code because I want to make a few more changes to this.state中,但我不能这样做,因为this.state始终为空,因为getNews似乎立即返回它具有的任何值。感谢您阅读这则长消息,你们真棒。

0 个答案:

没有答案
相关问题