【发布时间】: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<any[]> 始终是一个空数组 [] 如果没有找到,则返回 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 => { return list });返回一个值 -
"返回一个值" ...当然,但是
func返回什么?undefined... -
因为异步代码保持异步
标签: javascript angular typescript