我是 JavaScript 新手,我正在尝试循环每个对象数组并在每个对象上执行一个函数。这个函数返回一个承诺,我需要返回到调用它的主函数。
下面是代码,
createTypes({types: [type1, type2, type3]}, false).as('createdTypes');
const createTypes = ({ count =1, types = new Array(count).fill(),}, skip = true) => {
let promiseChain;
types.forEach(type => {
if (!skip) {
promiseChain = cy.createType(type, false);
} else {
promiseChain = cy.createType(type);
}
}
return promiseChain;
}
在上面的代码中,我正在对每种类型执行 createType 方法。如果skip为假,那么我想用type和false执行createType。如果skip为true,我想仅使用类型执行createType。 createType 方法返回一个承诺。
因此,对于每种类型,都会返回一个承诺,我想将所有承诺存储在一个变量(对象数组)中,并将其返回给调用函数。
在上面的代码中,仅保存最后执行类型的承诺。
我怎样才能将所有的承诺存储在一个中。有人可以帮我解决这个问题吗?谢谢
将它们全部收集到数组中,然后返回该数组?
const createTypes = ({ count = 1, types = new Array(count).fill(), }, skip = true) => {
const promiseArray = types.map(type => {
if (!skip) {
return cy.createType(type, false);
} else {
return cy.createType(type);
}
});
return Promise.all(promiseArray);
}