Asynchronous JavaScript Cheat Sheet
- Promises start in a pending state, neither fulfilled or rejected.
- When the operation is completed, a promise will become fulfilled with a value.
- If the operation fails, a promise will get rejected with an error.
- The function passed to the
Promise
constructor will execute synchronously.
- Use
resolve()
or reject()
to create promises from values.
Promise.resolve(val)
will fulfill the promise with val
.
Promise.reject(err)
will reject the promise with err
.
- If you put a fulfilled promise into a fulfilled promise, they will collapse into one.
new Promise((resolve, reject) => {
performOperation((err, val) => {
if (err) reject(err);
else resolve(val);
});
});
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
promisedOperation()
.then(
val => value + 1,
err => {
if (err === someKnownErr) return defaultVal;
else throw err;
}
)
.catch(
err => console.log(err);
)
.finally(
() => console.log('Done');
);
- All three of the above methods will not be executed at least until the next tick, even for promises that already have an outcome.
Promise.all()
turns an array of promises into a promise of an array.
- If any promise is rejected, the error will pass through.
Promise.race()
passes through the first settled promise.
Promise
.all([ p1, p2, p3 ])
.then(([ v1, v2, v3 ]) => {
});
Promise
.race([ p1, p2, p3 ])
.then(val => {
});
- Calling an
async
function always results in a promise.
(async () => value)()
will resolve to value
.
(async () => throw err)()
will reject with an error.
await
waits for a promise to be fulfilled and returns its value.
await
can only be used in async
functions.
await
also accepts non-promise values.
await
always waits at least until the next tick before resolving, even when waiting already fulfilled promises or non-promise values.
async () => {
try {
let val = await promisedValue();
} catch (err) {
}
}