Skip to content

Instantly share code, notes, and snippets.

@smspillaz
Last active February 16, 2019 07:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smspillaz/a61ffb4fd46c172b17c656206cd0b203 to your computer and use it in GitHub Desktop.
Save smspillaz/a61ffb4fd46c172b17c656206cd0b203 to your computer and use it in GitHub Desktop.
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