Skip to content

Instantly share code, notes, and snippets.

@kyptov
Created October 26, 2016 15:39
Show Gist options
  • Save kyptov/ff6984cf3eac7baf0e0a680e5987b70d to your computer and use it in GitHub Desktop.
Save kyptov/ff6984cf3eac7baf0e0a680e5987b70d to your computer and use it in GitHub Desktop.
Async/await analog with promises
let spammers = [];
getUser()
.catch(onGetUserErrorHandler)
.then(getSpammer)
.then(() => console.log(spammers));
function getSpammer(user) {
if (user === null) {
return;
}
if (spammers.length === 10) {
return;
}
return isSpammer(user)
.then((isSpammer) => isSpammer && spammers.push(user))
.catch(onSpammerCheckErrorHandler)
.then(getUser)
.catch(onGetUserErrorHandler)
.then(getSpammer);
}
function onSpammerCheckErrorHandler(error) {
console.log(error);
}
function onGetUserErrorHandler(error) {
console.log(error);
}
let users = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19][Symbol.iterator]();
function getUser() {
return new Promise(function (resolve) {
setTimeout(function () {
let user = users.next();
resolve(user.done ? null : user.value)
}, 100)
});
}
function isSpammer(user) {
return new Promise(function (resolve) {
setTimeout(function () {
resolve(user > 12)
}, 100)
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment