javascript - 从链式承诺返回映射数组
问题描述
function createDataSet(username, region, champion, amount) {
var dataArray = []; //what I want to return, if possible with .map()
return getUserId(username, region) //required for getUserMatchlist()
.then(userId => {
getUserMatchlist(userId, region, champion, amount); //returns an array of objects
})
.then(matchlist => {
matchlist.forEach(match => {
getMatchDetails(match.gameId.toString(), region) //uses the Id from the matchlist objects to make another api request for each object
.then(res => {
dataArray.push(res); //every res is also an object fetched individually from the api.
// I would like to return an array with all the res objects in the order they appear in
})
.catch(err => console.log(err));
});
});
}
我正在尝试将从多个 api 获取的数据发送到我的前端。获取数据不是问题,但是,使用.map()
没有用,而且从我读过的内容来看,promise 不能很好地工作。我返回该对象的最佳方式是什么?(函数会在收到get请求后执行,并dataArray
返回)
解决方案
Promise.all(listOfPromises)
将解析为一个数组,其中包含listOfPromises
.
要将其应用于您的代码,您需要类似(伪代码):
Promise.all(matchlist.map(match => getMatchDetails(...)))
.then(listOfMatchDetails => {
// do stuff with your list!
});
推荐阅读
- c++ - MSVC 查找符号的来源
- sql - 根据过去 31 天每天的情况滚动唯一计数
- javascript - Javascript - 使用属性而不使用对象将 HTML 页面加载到另一个页面中,我希望它直接在我的页面中
- python - 如何在 Python Turtle 中使用自定义本地字体?
- c++ - 如何允许在具有相同底层结构的模板类的指针类型之间进行转换?
- django - Django 我的 heroku 帐户无权更改我自己的应用程序
- python - Flask 会话 Cookie 过期
- python - Python禁用命令行模块的日志记录
- spartacus-storefront - 为 OCC_BACKEND_BASE_URL_VALUE 提取 JS 店面 URL”
- c# - 在 C# 中尝试将输入作为整数接收时检测到错误