Created
October 26, 2016 15:39
-
-
Save kyptov/ff6984cf3eac7baf0e0a680e5987b70d to your computer and use it in GitHub Desktop.
Async/await analog with promises
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
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