Created
December 6, 2019 11:41
-
-
Save dwaps/4ae1d8b630b62765680ec31b45ff7b42 to your computer and use it in GitHub Desktop.
ES6: Notion de promesse.
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
// Model | |
class User { | |
constructor(name, role) { | |
this.name = name; | |
this.role = role; | |
} | |
} | |
// BDD | |
const users = [ | |
new User('Patrick', 'ANONYME'), | |
new User('Aurélie', 'ADMIN'), | |
new User('Emilie', 'ANONYME'), | |
]; | |
// ------- | |
// Client | |
// ------- | |
// Création de la promesse | |
function getUsers(role) { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
const t = users.filter((user) => user.role === role); | |
if (t.length === 0) { | |
reject(`Il n'y a pas d'utilisateurs ayant ce role.`) | |
} | |
else { | |
resolve(t); | |
} | |
}, 3000); | |
}); | |
} | |
// Utilisation de la promesse | |
getUsers('EDITOR') | |
.then(tabUsers => { | |
console.log('\nUtilisateurs récupérés:'); | |
for (let u of tabUsers) { | |
console.log(u.name); | |
} | |
}) | |
.catch(error => console.log(error)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment