Skip to content

Instantly share code, notes, and snippets.

@jcuffe
Created March 30, 2021 22:45
Show Gist options
  • Save jcuffe/3522129266427c3940f9193605a2f588 to your computer and use it in GitHub Desktop.
Save jcuffe/3522129266427c3940f9193605a2f588 to your computer and use it in GitHub Desktop.
Nested `await` demo
// 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