Asynchronous Cheatsheet: Pending Promises Can Become Either... Fulfilled With A Value, Or... Rejected With An Error

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

asynchronous JS cheatsheet Combining promises

Pending promises can become either... Use all() to turn an array of promises into a promise to an If any promise is rejected, the error will be passed Use race() instead to pass through the first settled
array. through. promise.
value Fulfilled with a value, or... Promise.all([
Promise.all([ Promise.race([
value1 , [value1 , ,
error Rejected with an error.
value2 , value2, , error , value
outcome Either way, they are settled with an outcome. value3 , value3] error , value ,
]) ]) ])

async/await promise.then( onFulfilled, onRejected ) promise.catch( onRejected )

Calling an async function always results in a promise. Calls onFulfilled once the promise is fulfilled. Behaves identically to then when onFulfilled is omitted.

(async () value) () value value .then( value nextValue , ? ) nextValue error .catch( onRejected ) error .then( ? , onRejected )

(async () outcome ) () outcome value .then( value outcome , ? ) outcome Passes fulfilled values through.

(async () throw error) () error value .then( value throw error , ? ) error value .catch( ) value

await waits for a promise to be fulfilled, then returns its Calls onRejected if the promise is rejected.
value. promise.finally( onFinally )
error .then( ? , error value ) value
async function() { Calls onFinally with no arguments once any outcome is available. Passes through input
try { error .then( ? , error outcome ) outcome
promise.
let value = await outcome error .then( ? , error throw nextError ) nextError
outcome .finally( () ) outcome
} Passes errors through if onRejected is undefined.
catch (error) { The onFulfilled, onRejected and onFinally functions will not be executed !
error .then( ) error until at least the next tick, even for promises that already have an outcome.
}
}

You can pass non-promise values to await


Making promises
const fn = async () {
let value = await value The function passed to new Promise will be executed synchronously. Use resolve() or reject() to create promises from values.

} Promise.resolve(value) value
new Promise((resolve, reject) {
doImportantStuff((error, value) { Promise.reject(error) error
await may only be used within async functions. ! if (error)
reject(error) If you put a fulfilled promise into a fulfilled promise, they'll collapse into one.
else
await will wait until at least the next tick before ! resolve(value) Promise.resolve( value ) value
returning, even when awaiting already-fulfilled promises })
or non-promise values. })
Sometimes you might not need reject, or might not resolve to a value.

function delay(milliseconds) {
return new Promise(resolve
setTimeout(resolve, milliseconds)
)
FRONTEND ARMORY }
frontarm.com

You might also like