如何解决如何在Proscript中将Promise统一为一个Promise
我需要在.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)
}
解决方法
您可以使用reduce函数来解决它,然后等待Promise。所有返回的promise数组。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。