【问题标题】:How to unite Promises into one Promise in Typescript如何在 Typescript 中将 Promise 合并为一个 Promise
【发布时间】:2020-12-08 01:23:56
【问题描述】:

我需要在 .map 之后用数据完成后返回 temp_data 但是,现在它总是返回未定义的值,因为我正在这样做:let temp_data: LooseObject = {}。但是没有这个,我就无法使用 LooseObject。有没有什么技巧可以帮助我解决这个问题?

    async getData(){
        let temp_data: LooseObject = {}
        this.categorylist.map((category: string) => {
            this.getByCategory(category).then((newsList) => {
                temp_data[category] = []
                newsList.forEach((article: Article) => {
                    temp_data[category].push(article)
                })
                console.log('Data: ',temp_data)
            })
        })
        
        return await temp_data
    }

更新: 这是我的 getByCategory 函数的示例:

async getByCategory(category: string) {
         const news = await this.newsapi.v2.topHeadlines({
            q: category,
            sortBy: 'popularity'
        })
         return await news.articles.map(this._transformArticle)
    }

【问题讨论】:

    标签: reactjs typescript async-await


    【解决方案1】:

    您可以通过使用 reduce 函数并等待 Promise.all 返回的承诺数组来解决它。

    【讨论】:

    • 我应该在哪里使用它?我看了一些手册,没有找到任何好的解释。
    • 这是一个很好的例子:gist.github.com/anvk/5602ec398e4fdc521e2bf9940fd90f84感谢帮助
    • 你有 getByCategory 函数的工作示例(可以是模拟的)吗?将帮助我向您展示我的意思:)
    猜你喜欢
    • 1970-01-01
    • 2022-11-29
    • 2017-10-11
    • 2016-12-26
    • 2017-11-18
    • 1970-01-01
    • 2022-11-22
    • 2018-12-14
    • 1970-01-01
    相关资源
    最近更新 更多