Last active
June 14, 2017 01:52
-
-
Save SakoMe/bc7fdccc3679056789781fc5427a19bc to your computer and use it in GitHub Desktop.
Promises vs async / await...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//SET UP | |
const users = [{ | |
id: 1, | |
name: 'Bob', | |
schoolId: 101 | |
}, { | |
id: 2, | |
name: 'Jane', | |
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 the id of ${id}.`); | |
} | |
}); | |
}; | |
const getGrades = (schoolId) => { | |
return new Promise((resolve, reject) => { | |
resolve(grades.filter((grade) => grade.schoolId === schoolId)); | |
}); | |
}; | |
//PROMISES.... | |
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.`; | |
}); | |
}; | |
//ASYNC AWAIT...... | |
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(3).then((status) => { | |
console.log(status); | |
}).catch((e) => { | |
console.log(e); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment