TS - 使用return从回调函数中分配值

时间:2017-12-04 04:13:48

标签: javascript angular typescript

我正在获取班级People数组的数据,每个人的出勤列表为Observable<any[]>

// Class person
class Person {
   id: number;
   name: string;
   attendance: Observable<any[]>; // An Observable array
}


// People array (I only use array for simplicity sake)
// NOTE: Every person has a list of attendance
people = Person[] = this.someService.getPeople(); 

现在我验证一些人是否可能有0长度的出勤,假设attendance: Observable<any[]>总是空数组[]如果没有找到,则返回false,否则为{{{ 1}}。

validateAttendance()

为了做到这一点,我试图在validateAttendance(): boolean { // Loop to each person and get attendance list. people.forEach(p => { // Get the list using a callback function. const func = (callback: (data) => void) => { // Get attendance using subscribe() method p.attendance.subscribe(list => { callback(list); }); } // An attempt to get the list from a callback function // Failed because return is undefined. const result = func(res => { console.log(res); // Got list of attendance of a given person. return res; }); if (result.length <= 0) { alert(`${p.name} has no attendance, must be a lazy one please check.`); return false; } }); return true; } 方法中创建一个回调函数,并从中返回出勤列表。 但结果变量未定义!

可以通过这种方式从回调函数返回一个值吗?

1 个答案:

答案 0 :(得分:1)

您的代码有几个问题:

  1. 它是异步的,因此该函数也需要异步(使用Promise
  2. func()未返回值,因此result将始终未定义。
  3. 您的代码深入alert()。你是否会为没有出席的每个人弹出?最好将逻辑和UI分开。
  4. 我已将您的代码修改为以下内容:

    function validateAttendance(people): Promise<boolean> {
      return getPeopleWithNoAttendance(people)
        .then(peopleWithNoAttendance => {
          if (peopleWithNoAttendance.length > 0) {
            // or loop though them
            alert(`${peopleWithNoAttendance[0].name} has no attendance, must be a lazy one please check.`);
            return false
          }
          return true
        })
    }
    
    function getPeopleWithNoAttendance(people) {
      return Promise.all(people.map(person => {
        return new Promise(r => {
          person.attendance.subscribe(r)
        }).then(attendance => {
          return attendance.length <= 0 ? person : undefined
        })
      })).then(listOfPeopleOrUndefined => {
        const listOfPeople = listOfPeopeleOrUndefined.filter(p => p)
        return listOfPeople
      })
    }
    

    同样改变的是传入people变量。如果这是类中的方法,请随意更改。