我有一个与此结构类似的代码。似乎我在这里不需要异步函数,但就像我说的那样,它类似于我自己的代码,有点长。
这是我的代码:
const array = [
{ methods: 'user.js'},
{ methods: 'test.js'},
{ methods: 'hello.js' },
];
async function bigTest() {
async function details() {
const arr = [];
const test = [];
const files = array.map(async (i) => {
arr.push({
name: i,
item: [
{
name: 'test',
},
],
});
return test.push(arr);
});
return Promise.all(files);
}
const result = await details();
console.log(JSON.stringify(result));
}
bigTest();
console.log(arr)
每次推入数组的过程中我的回报:
[ { name: { methods: 'user.js', item: [] }, item: [ [Object] ] } ]
[ { name: { methods: 'user.js', item: [] }, item: [ [Object] ] },
{ name: { methods: 'test.js', item: [] }, item: [ [Object] ] } ]
[ { name: { methods: 'user.js', item: [] }, item: [ [Object] ] },
{ name: { methods: 'test.js', item: [] }, item: [ [Object] ] },
{ name: { methods: 'hello.js', item: [] }, item: [ [Object] ] } ]
我想返回包含所有推送元素的最后一个数组,但结果是 [1,2,3]
当我对阵列测试执行 console.log 时,我得到重复的对象
我想返回包含所有推送元素的最后一个数组,但结果是
[1,2,3]
来自MDN:
push() 方法将一个或多个元素添加到数组的末尾并返回数组的新长度。
所以你需要返回元素本身而不是test.push(arr)
. 替换return test.push(arr)
为:
test.push(arr);
return test[test.length-1];
然后console.log
只有最后一项result
:
console.log(JSON.stringify(result[result.length-1]));
const array = [
{ methods: 'user.js', item: [] },
{ methods: 'test.js', item: [] },
{ methods: 'hello.js', item: [] },
];
async function bigTest() {
async function details() {
const arr = [];
const test = [];
const files = array.map(async (i) => {
arr.push({ name: i, item: [{ name: 'test' }] });
test.push(arr);
return test[test.length-1];
});
return Promise.all(files);
}
const result = await details();
console.log(JSON.stringify(result[result.length-1]));
}
bigTest();
我假设您正在使用arr
和test
用于其他用途,否则,您可以通过摆脱中间数组并记录整个结果数组来稍微简化您的代码:
const array = [
{ methods: 'user.js', item: [] },
{ methods: 'test.js', item: [] },
{ methods: 'hello.js', item: [] },
];
async function bigTest() {
async function details() {
return Promise.all(array.map(async (i) =>
({ name: i, item: [{ name: 'test' }] })
));
}
const result = await details();
console.log(JSON.stringify(result));
}
bigTest();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句