Skip to content

Instantly share code, notes, and snippets.

@ehpc
Created January 27, 2020 17:04
Show Gist options
  • Save ehpc/496f0941bd55a02a0b7523d9ed240388 to your computer and use it in GitHub Desktop.
Save ehpc/496f0941bd55a02a0b7523d9ed240388 to your computer and use it in GitHub Desktop.
Examples of dIfferent async patterns in JavaScript
/**
* Разные асинхронные паттерны в JS, решающие одну и ту же задачу
*/
///////////////// callbacks ///////////////////////////////////
function asyncFunction(callback) {
setTimeout(callback.bind(this, 42), 100);
}
asyncFunction(console.log.bind(this, 'asyncFunction:'));
///////////////// promises ///////////////////////////////////
const promise = new Promise(resolve => {
setTimeout(resolve.bind(this, 42), 100);
});
promise.then(console.log.bind(this, 'new Promise:'));
///////////////// async/await ////////////////////////////////
async function myFunction() {
return new Promise(resolve => {
setTimeout(resolve.bind(this, 42), 100);
});
}
(async () => {
console.log('async function', await myFunction());
})();
///////////////// generators w/ async/await /////////////////
function* generatorFabric() {
yield new Promise(resolve => {
setTimeout(resolve.bind(this, 42), 100);
});
}
const generator = generatorFabric();
(async () => {
for await (const result of generator) {
console.log('generator:', result);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment