当Promise.all完成其返回包含数据数组的数组.在我的例子中,数组只是数字:
[
[ 1, 4, 9, 9 ],
[ 4, 4, 9, 1 ],
[ 6, 6, 9, 1 ]
]
Run Code Online (Sandbox Code Playgroud)
阵列可以是任何大小.
目前我这样做:
let nums = []
data.map(function(_nums) {
_nums.map(function(num) {
nums.push(num)
})
})
Run Code Online (Sandbox Code Playgroud)
有没有其他方法可以做到这一点?是否lodash有一个能够做到这一点的任何功能?
我会这样做;
var a = [
[ 1, 4, 9, 9 ],
[ 4, 4, 9, 1 ],
[ 6, 6, 9, 1 ]
],
b = [].concat(...a)
console.log(b)Run Code Online (Sandbox Code Playgroud)
data.reduce(function (arr, row) {
return arr.concat(row);
}, []);
Run Code Online (Sandbox Code Playgroud)
或者,concat和apply:
Array.prototype.concat.apply([], data);
Run Code Online (Sandbox Code Playgroud)
您实际上不需要任何类型的库来执行此操作,您可以使用concatwith apply:
Promise.all(arrayOfPromises).then((arrayOfArrays) => {
return [].concat.apply([], arrayOfArrays);
});
Run Code Online (Sandbox Code Playgroud)
但是,如果您使用的是 lodash,则可以使用它_.flatten(arrayOfArrays)来达到相同的效果。
如果使用 async/await,要扩展 @Retsam 的答案,你可以这样做
const mergedArray = []
.concat
.apply([], await Promise.all([promise1, promise2, promiseN]));
Run Code Online (Sandbox Code Playgroud)
我使用 AWS SDK 完成的一个真实示例,从多个 IAM 用户组获取用户名列表
const users = await getActiveUsersByGroup(['group1', 'group2'])
async function getActiveUsersByGroup(groups = []) {
getUsersByGroupPromises = groups.map(group => getUsersByGroup(group));
const users = []
.concat
.apply([], await Promise.all(getUsersByGroupPromises)) // Merge (concat) arrays
.map(users => users.UserName); // Construct new array with just the usernames
return users;
}
async function getUsersByGroup(group) {
const params = {
GroupName: group,
MaxItems: 100 // Default
};
const { Users: users } = await iam.getGroup(params).promise();
return users;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4468 次 |
| 最近记录: |