Skip to content

Instantly share code, notes, and snippets.

@marcobiedermann marcobiedermann/promise.js
Last active Oct 18, 2019

Embed
What would you like to do?
Promise Cheatsheet
// 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
You can’t perform that action at this time.