Skip to content

Instantly share code, notes, and snippets.

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

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([
// … assign result to individual variables
const [ createdUserA, createdUserB ] = await Promise.all([
// 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: `` must return a value
const userIds = ['1', '2', '3'];
const users = await Promise.all( => getUserById(userId)));
// add check / condition within loop
const users = await Promise.all( => {
if (!userId) {
return null;
return getUserById(userId)
// better: use `Array.prototype.filter()`
const users = await Promise.all(
.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.