Created
March 30, 2021 22:45
-
-
Save jcuffe/3522129266427c3940f9193605a2f588 to your computer and use it in GitHub Desktop.
Nested `await` demo
This file contains hidden or 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
// Query builders are not actually promises, but have a `.then()` method which matches the promise interface. | |
// As soon as you `await` or `.then()` the builder, the query is executed, and a new promise is generated that will contain the result. | |
const getQueryBuilder = () => ({ | |
then: (resolve) => | |
resolve( | |
new Promise((resolve) => | |
setTimeout(() => resolve(["query", "results"]), 1000), | |
), | |
), | |
}) | |
// This method does nothing but wrap the query builder in a promise | |
const modifyQueryBuilder = async (queryBuilder) => { | |
await new Promise((resolve) => setTimeout(resolve, 1000)) | |
return queryBuilder | |
} | |
// When we await the modification method, we also await the query's results | |
const execute = async () => { | |
const queryBuilder = getQueryBuilder() | |
const modifiedQueryBuilder = await modifyQueryBuilder(queryBuilder) | |
// Prints ['query', 'results'] | |
console.log(modifiedQueryBuilder) | |
} | |
execute() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment