Last active
October 18, 2019 20:27
-
-
Save marcobiedermann/2173f4f0ddf7b86582bc9778703a2079 to your computer and use it in GitHub Desktop.
Promise Cheatsheet
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
// await must only be used if you want to execute something after promise to await the result | |
const createdUser = await createUser(); | |
const user = await getUser(); | |
// async must be used in function if you want to await something | |
(async () => { | |
await foo(); | |
})() | |
// if you return the promise, `await` is not needed | |
// execute promise and assign result to a variable | |
const user = await getUser(); | |
// execute multiple promises in parallel and assign result to a variable | |
const createdUsers = await Promise.all([ | |
createUser(), | |
createUser(), | |
]); | |
// … assign result to individual variables | |
const [ createdUserA, createdUserB ] = await Promise.all([ | |
createUser(), | |
createUser(), | |
]); | |
// when using array like objects like Map, Set, Node you have to "borrow" some functions | |
const users = new Map() | |
Array.from(users).map(user => …) | |
// execute multiple promises in sequence and assign result to a variable | |
// Important: `Array.prototype.map` must return a value | |
const userIds = ['1', '2', '3']; | |
const users = await Promise.all(userIds.map(userId => getUserById(userId))); | |
// add check / condition within loop | |
const users = await Promise.all(userIds.map(userId => { | |
if (!userId) { | |
return null; | |
} | |
return getUserById(userId) | |
})); | |
// better: use `Array.prototype.filter()` | |
const users = await Promise.all( | |
userIds | |
.filter(userId => userId) | |
.map(userId => getUserById(userId)) | |
); | |
// execute different promise based on condition | |
// if must be wrapped in function | |
function getUserByIdOrSlug(idOrSlug) { | |
if (!isUUID(idOrSlug)) { | |
return getUserBySlug(idOrSlug); | |
} | |
return getUserById(idOrSlug); | |
} | |
const user = await getUserByIdOrSlug(idOrSlug); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment