Created
January 27, 2020 17:04
-
-
Save ehpc/496f0941bd55a02a0b7523d9ed240388 to your computer and use it in GitHub Desktop.
Examples of dIfferent async patterns in JavaScript
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
/** | |
* Разные асинхронные паттерны в 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