-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.promises.js
80 lines (70 loc) · 1.71 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
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 getGrades = (schoolId) => {
return new Promise((resolve, reject) => {
resolve(grades.filter((grade) => grade.schoolId === schoolId));
});
};
// Andrew has a 83% in the class
const getStatus = (userId) => {
let user;
return getUser(userId).then((tempUser) => {
user = tempUser;
return getGrades(user.schoolId);
}).then((grades) => {
let average = 0;
if (grades.length > 0) {
average = grades.map((grade) => grade.grade).reduce((a, b) => a + b) / grades.length;
}
return `${user.name} has a ${average}% in the class.`;
});
};
const getStatusAlt = async (userId) => {
const user = await getUser(userId);
const grades = await getGrades(user.schoolId);
let average = 0;
if (grades.length > 0) {
average = grades.map((grade) => grade.grade).reduce((a, b) => a + b) / grades.length;
}
return `${user.name} has a ${average}% in the class.`;
};
getStatusAlt(2).then((status) => {
console.log(status);
}).catch((e) => {
console.log(e);
});
// getStatus(123).then((status) => {
// console.log(status);
// }).catch((e) => {
// console.log(e);
// });