Last active
February 16, 2019 07:56
-
-
Save smspillaz/a61ffb4fd46c172b17c656206cd0b203 to your computer and use it in GitHub Desktop.
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
import fs from 'fs'; | |
function oldStyleAsynchronousFunction(callback) { | |
fs.readFile('somefile.txt', 'utf8', function(err, result) { | |
if (err) { | |
callback(err, null); | |
return; | |
} | |
callback(result); | |
}); | |
} | |
function functionReturningPromise() { | |
return new Promise((resolve, reject) => { | |
try { | |
oldStyleAsynchronousFunction((err, result) => | |
err !== null ? reject(err) : resolve(result) | |
); | |
} catch (e) { | |
reject(e); | |
} | |
}); | |
} | |
async function myAsync() { | |
/* Anything that returns a promise can be "awaited" */ | |
let a = await functionReturningPromise(); | |
return a; | |
} | |
/* Awaiting is the same as doing this */ | |
function functionThatUsesPromise() { | |
return functionReturningPromise().then(() => someOtherThing()); | |
} | |
/* What happens if you have multiple awaits in a single function? */ | |
function myAsyncLotsOfAwaits() { | |
let a = await functionReturningPromise(); | |
let b = await functionReturningPromise(a); | |
let c = await functionReturningPromise(c); | |
return c; | |
} | |
/* It is the same thing as doing this */ | |
function functionThatUsesPromiseChain() { | |
return functionThatUsesPromise.then(a => | |
functionThatUsesPromise(a) | |
).then(b => | |
functionThatUsesPromise(b) | |
).then(c => | |
functionThatUsesPromise(c) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment