-
-
Save tkw1536/4fe9560f045abc6f5b2ff96f6bcf54e6 to your computer and use it in GitHub Desktop.
Connect Platform Feedback
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
// we use these functions | |
function doA(): Promise<A> | |
function doB(inB: A): Promise<B> | |
function doC(inC: A): Promise<C> | |
function doD(inD: B): Promise<D> | |
function doD(inE: C): Promise<E> | |
function doF(a: D, b: E): Promise<F> | |
// this is the example from your website | |
// which indeed looks very bad | |
function yourCode() { | |
doA().then(function (outA) { | |
Promise.all([ | |
new Promise(function (resolve) { | |
return | |
doB(outA).then(function (outB) { | |
doD(outB).then(function (outD) { | |
resolve(outD); | |
}); | |
}); | |
}), | |
new Promise(function (resolve) { | |
doC(outA).then(function (outC) { | |
doE(outC).then(function (outE) { | |
resolve(outE); | |
}); | |
}); | |
}) | |
]).then(function (values) { | |
doF(values[0], values[1]); | |
}); | |
}); | |
} | |
// but Promises can actually return Promises, which makes chaining extremly nice. | |
// see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#Chaining | |
// also arrow functions and pattern matching, but that's really just syntactic sugar | |
// here is the same code again, which already looks a lot cleaner: | |
function properPromiseCode() { | |
return doA().then((outA) => | |
Promise.all([ | |
doB(outA).then(doD), | |
doC(outA).then(doE) | |
]) | |
).then(([outD, outE]) => doF(outD, outE)); | |
} | |
// Doesn't look to bad does it? | |
// Also, lets look at ASync functions (ES2017) | |
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function | |
// this code looks a little uglier than above, but resembles synchronous code. | |
async function asyncFunctionCode() { | |
const outA = await doA(); | |
async function B_D(inB) { | |
const outB = await doB(inB); | |
return await doD(outB); | |
} | |
async function C_E(inC) { | |
const outC = await doC(inC); | |
return await doD(outB); | |
} | |
const [outD, outE] = await Promise.all([B_D(outA), C_E(outA)]); | |
return await doF(outD, outE); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment