-
Notifications
You must be signed in to change notification settings - Fork 0
/
app-promises.js
88 lines (79 loc) · 1.73 KB
/
app-promises.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
const users = [{
id: 1,
name: 'Andrew',
schoolId: 101
},{
id: 2,
name: 'Jessica',
schoolId: 999
}];
const grades = [{
id: 1,
schoolId: 101,
grade: 86
}, {
id: 2,
schoolId: 999,
grade: 100
}, {
id: 3,
schoolId: 101,
grade: 80
}];
const getUser = (id) => {
return new Promise((resolve, reject) => {
const user = users.find((user) => user.id === id);
if (user) {
resolve(user)
} else {
reject(`Unable to find user with id of ${id}.`);
}
});
};
const getStatus = (userId) => {
var user;
return getUser(userId).then((tempUser) => {
user = tempUser;
return getGrades(user.schoolId);
}).then((grades) => {
var avg = 0;
if (grades.length > 0) {
avg = grades.map((grade) => grade.grade).reduce((a, b) => a+b)/grades.length;
}
return `${user.name} has a ${avg}% in the class.`;
})
};
const getStatusAlt = async (userId) => {
const user = await getUser(userId);
const grades = await getGrades(user.schoolId);
var avg = 0;
if (grades.length > 0) {
avg = grades.map((grade) => grade.grade).reduce((a, b) => a+b)/grades.length;
}
return `${user.name} has a ${avg}% in the class.`;
};
getStatusAlt(1).then((status) => {
console.log(status);
}).catch((e) => {
console.log(e);
});
// getUser(3).then((user) => {
// console.log(user);
// }).catch((e) => {
// console.log(e);
// });
const getGrades = (schoolId) => {
return new Promise((resolve, reject) => {
resolve(grades.filter((grade) => grade.schoolId === schoolId));
});
};
// getGrades(101).then((grade) => {
// console.log(grade);
// }).catch((e) => {
// console.log(e);
// });
// getStatus(1).then((status) => {
// console.log(status);
// }).catch((e) => {
// console.log(e);
// });