【问题标题】:TS - assign value from a callback function using returnTS - 使用 return 从回调函数中赋值
【发布时间】:2017-12-04 04:13:48
【问题描述】:

我正在获取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&lt;any[]&gt; 始终是一个空数组 [] 如果没有找到,则返回 false 否则返回 true 到 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;
}

为了做到这一点,我尝试在validateAttendance() 方法中创建一个回调函数并从中返回出勤列表。 但是结果变量未定义!

这样可以从回调函数中返回值吗?

【问题讨论】:

  • 如果validateAttendance 中的任何代码是异步的(例如,`p.attendance.subscribe` 看起来是异步的),那么无论您添加多少时髦的回调,都无法同步返回结果
  • @JaromandaX 谢谢我真的应该改变方法,但我真的认为我们可以从func(list =&gt; { return list });返回一个值
  • "返回一个值" ...当然,但是 func 返回什么? undefined ...
  • 因为异步代码保持异步

标签: javascript angular typescript


【解决方案1】:

您的代码有几个问题:

  1. 它是异步的,所以函数也需要异步(使用Promise
  2. func() 不返回值,因此 result 将始终未定义。
  3. 您的代码中有alert()。你会弹出每个没有出席的人吗?最好将逻辑和 UI 分开。

我已将您的代码修改为以下内容:

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 变量。如果这是类中的方法,请随意更改。

【讨论】:

  • 好,这是我真的改变了我的方法来返回 Promise,效果很好
  • return new Promise(r =&gt; { person.attendance.subscribe(r) } 可以更简洁地写成return person.attendance.toPromise()
猜你喜欢
  • 1970-01-01
  • 2021-08-23
  • 2014-06-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多