// Resolving with a valuePromise.resolve(42).then(val => console.log(val)); // 42// Rejecting with an errorPromise.reject(new Error('Failed')).catch(err => console.log(err.message)); // 'Failed'
// Resolving with a value, rejecting with an errornew Promise((resolve, reject) => { performOperation((err, val) => { if (err) reject(err); else resolve(val); });});// Resolving without value, no need for rejectconst delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
If you put a fulfilled promise into a fulfilled promise, they will collapse into one.
Promise.prototype.then() accepts two optional arguments (onFulfilled, onRejected):
promisedOperation() .then( val => val + 1, // Called once the promise is fulfilled err => { // Called if the promise is rejected if (err === someKnownErr) return defaultVal; else throw err; } );
Turns an array of promises into a promise of an array:
Promise .all([ p1, p2, p3 ]) .then(([ v1, v2, v3 ]) => { // Values always correspond to the order of promises, // not the order they resolved in (i.e. v1 corresponds to p1) });
If any promise is rejected, Promise.all() will immediately reject with that error.
JavaScript promises are asynchronous, meaning they execute in parallel. To execute promises one after another (sequentially), chain them using Array.prototype.reduce():
const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve());const delay = d => new Promise(r => setTimeout(r, d));runPromisesInSeries([() => delay(1000), () => delay(2000)]);// Executes each promise sequentially, taking a total of 3 seconds to complete
Each promise in the chain returns the next promise when resolved, using Promise.prototype.then().