我正在编写一个函数,该函数使用给定类型的数据返回promise。我的实体名称是Groups
,我想返回一个组Groups[]
的数组这是我的功能
async filterGroupsByAvailableSpots (groups: Groups[] ) :Promise<Groups[]> {
let groupsAvailableToMatch : Groups[] = [] ;
let searchAvailableGroupsLoop = new Promise((resolve, reject) => {
groups.forEach((group, index, array) => {
this.getStudentsByActiveGroup (group.id)
.then((students) => {
//If the group have spots to match
if (students.length < 6) {
groupsAvailableToMatch.push(group)
}
// Stop FLag
if (index === array.length -1) {
resolve(groupsAvailableToMatch);
}
})
});
});
return searchAvailableGroupsLoop;
}
但我在退货承诺中遇到错误
let searchAvailableGroupsLoop: Promise<unknown>
Type '{}' is missing the following properties from type 'Groups[]': length, pop, push, concat, and 26 more.ts(2740)
我认为TS无法推断返回变量的类型,请尝试在创建promise 时指定类型
let searchAvailableGroupsLoop = new Promise<Groups[]>((resolve, reject) => {
您需要解决每个案例的Promise。如果在您的组数组中没有"0";停止标志";你的诺言定为{}
。因此,如果更适合您的需求,请使用空数组进行解决,或者使用错误进行拒绝。
async filterGroupsByAvailableSpots (groups: Groups[] ) :Promise<Groups[]> {
let groupsAvailableToMatch : Groups[] = [] ;
let searchAvailableGroupsLoop = new Promise((resolve, reject) => {
groups.forEach((group, index, array) => {
this.getStudentsByActiveGroup (group.id)
.then((students) => {
//If the group have spots to match
if (students.length < 6) {
groupsAvailableToMatch.push(group)
}
// Stop FLag
if (index === array.length -1) {
resolve(groupsAvailableToMatch);
}
})
});
resolve([]); // add this line or reject("Error");
});
return searchAvailableGroupsLoop;
}