Last active
August 8, 2023 09:21
-
-
Save joeytwiddle/ff0a9cf92be0366b274e4283a8b5a935 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
async function getFoo (bar) { | |
const baz = 2 * bar; | |
const root = await asyncSqrt(baz); | |
return 2 * root; | |
} | |
// Is the same as | |
function getFoo (bar) { | |
return Promise.resolve().then(() => { | |
const baz = 2 * bar; | |
return asyncSqrt(baz).then(root => { | |
return 2 * root; | |
}); | |
}); | |
} | |
// (Aside) It is not quite the same as | |
function getFoo (bar) { | |
const baz = 2 * bar; | |
return asyncSqrt(baz).then(root => { | |
return 2 * root; | |
}); | |
} | |
// because if 2 * bar threw an error, this function would throw an error, | |
// but the other functions would return a rejected promise. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for the clarification Tobi. Perhaps I should have written "is basically equivalent to" instead of "is the same as".
Technically, using
Promise.resolve().then()
in my example is unnecessary, but I like to use it to start a promise chain, so we can forget about the need to call theresolve()
orreject()
callbacks. While less efficient for the engine, I think this reduces cognitive load. Since we may have a chain of many.then()
s, I like to make the first code block the same as the rest.Of course
new Promise((resolve, reject) => ...)
is highly suitable for converting callback-style functions into promises, but I don't really enjoy using it to start a promise chain in business logic.