My Docs
BlogGithubLinkedin
Cheat Sheets
Cheat Sheets
  • πŸ“‹Cheat Sheets
    • Files
    • Terminal Cheat Sheet
    • Flexbox Cheat Sheet
    • Common HTTP status codes Cheat Sheet
    • networking_cheatsheet
    • Regular Expressions Cheat Sheet
    • REGEX units Cheat Sheet
  • bash_cheatsheet
  • Google dork cheatsheet
  • Cheatsheet-v2
  • πŸ•ΈοΈπŸ’» πŸ’» Javascript
    • JavaScript
      • Javascript Python cheatsheet
      • General
        • JavaScript Promise API Cheat Sheet
        • Chai.js
        • Canvas
        • ES6 EXPORTS
        • Asynchronous JavaScript Cheat Sheet
      • React
        • React Cheat Sheet
          • React Component Guide
        • React Patterns:
        • react-examples
        • React.js
          • Bootstrap
        • React.js cheatsheet 2
        • React-router
        • React.js (v0.14)
        • React.js
        • React Patterns:
      • βš–οΈLibraries & Frameworks
        • LOADASH Cheat Sheet
        • sequelize_cheatsheet
        • Sequelize Cheatsheet
      • Node & Express
        • ExpressJS Cheat Sheet
      • CHEATSHEET
      • NPM Cheat Sheet
        • NPM Command Line Cheat Sheet
      • Function Context Cheatsheet
      • js-model
  • πŸ’»CS-Concepts
    • Computer Science Concepts
      • Data Structures
        • The Queue data structure
        • Cheat Sheet for Beginners: JavaScript Data Structures Methods
        • MDN Web Docs Glossary: Definitions of Web-related terms \| MDN
        • Data Structures Cheat Sheet
        • The Tree data structure
        • An Executable Data Structures Cheat Sheet for Interviews
      • networking_cheatsheet
  • Tools
    • πŸ› οΈTools
      • VSCODE Cheat Sheet
      • Emmet
  • πŸ“ΌGuides-Tutorials
    • Tutorials
      • React.js
  • JavaScript Arrays
  • editorconfig
  • AWS CLI
  • ES6 EXPORTS
  • Flynn
  • Github
    • Github
      • Github Cheat Sheet
    • git log
    • GITHUB Cheat Sheet
      • An Executable Data Structures Cheat Sheet for Interviews
      • graphs_cheatsheet
  • General
    • General
  • πŸ‘¨β€πŸ’»πŸ‘¨πŸ’» πŸ‘¨πŸ’» πŸ’» Programming Languages
    • 🐍Python:
      • Python
        • What is Python
      • Regex In Python
    • HTML
  • EC2 API tools
    • MARKDOWN
    • πŸ§˜β™‚ PSQL
      • POSTGRES
      • postgreSQL_cheatsheet
  • ES6 IMPORTS
    • bash_cheatsheet
    • cleancode
    • πŸ”¨Bash
      • Bash Cheat Sheet
      • Learn Bash Scripting: Bash Scripting Cheatsheet
      • Curl
      • Bash Shortcuts Cheat Sheet
      • SSH Cheatsheet
      • Linux
    • CSS
      • CSS
        • CSS Grid
        • cssnext
        • CSS Cheat Sheet
        • CSS Flex Box
        • CSS tricks
        • CSS selectors
        • cssnext
        • CSS background
        • CSS animations
    • Typescript
  • Computer Science Concepts
    • An Executable Data Structures Cheat Sheet for Interviews
    • graphs_cheatsheet
    • networking_cheatsheet
    • Firebase
    • networking_cheatsheet
    • πŸ›Heroku Cheat Sheet
    • Binary Tree
  • πŸ“šDocs
    • Docs
      • editorconfig
      • EC2 API tools
      • Asynchronous JavaScript Cheat Sheet
      • CHEATSHEET (3)
      • js-model
      • Emmet
      • Binary Tree
      • Python
      • Contributor Covenant Code of Conduct
      • networking_cheatsheet
      • Common HTTP status codes Cheat Sheet
      • AWS CLI
      • Linux
      • networking_cheatsheet
      • React Patterns:
      • MDN Web Docs Glossary: Definitions of Web-related terms \| MDN
      • JavaScript Arrays
      • Linux
      • Javascript Python cheatsheet
      • Cheatsheet-v2
      • Binary Tree
      • Heroku Cheat Sheet
      • Asynchronous JavaScript Cheat Sheet
      • Cheatsheet Compilation
      • AWS CLI
      • EC2 API tools
      • Common HTTP status codes Cheat Sheet
      • Firebase
      • The Queue data structure
      • Cheat Sheet for Beginners: JavaScript Data Structures Methods
Powered by GitBook
On this page

Was this helpful?

Edit on GitHub
  1. Docs
  2. Docs

Asynchronous JavaScript Cheat Sheet

Promise basics

  • 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.

Creating promises

  • The function passed to a new Promise 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.

// Resolving with a value, rejecting with an error
new Promise((resolve, reject) => {
  performOperation((err, val) => {
    if (err) reject(err);
    else resolve(val);
  });
});

// Resolving without value, no need for reject
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

Handling promises

  • Promise.prototype.then() accepts two optional arguments (onFulfilled, onRejected).

  • Promise.prototype.then() will call onFulfilled once the promise is fulfilled.

  • Promise.prototype.then() will call onRejected if the promise is rejected.

  • Promise.prototype.then() passes errors through if onRejected in undefined.

  • Promise.prototype.catch() accepts one argument (onRejected).

  • Promise.prototype.catch() behaves like Promise.prototype.then() when onFulfilled is omitted.

  • Promise.prototype.catch() passes fulfilled values through.

  • Promise.prototype.finally() accepts one argument (onFinally).

  • Promise.prototype.finally() calls onFinally with no arguments once any outcome is available.

  • Promise.prototype.finally() passes through input promise.

promisedOperation()
  .then(
    val => value + 1,   // Called once the promise is fulfilled
    err => {            // Called if the promise is rejected
      if (err === someKnownErr) return defaultVal;
      else throw err;
    }
  )
  .catch(
    err => console.log(err); // Called if the promise is rejected
  )
  .finally(
    () => console.log('Done'); // Called once any outcome is available
  );
  • All three of the above methods will not be executed at least until the next tick, even for promises that already have an outcome.

Combining promises

  • 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 ]) => {
    // Values always correspond to the order of promises,
    // not the order they resolved in (i.e. v1 corresponds to p1)
  });

Promise
  .race([ p1, p2, p3 ])
  .then(val => {
    // val will take the value of the first resolved promise
  });

async/await

  • 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();
    // Do stuff here
  } catch (err) {
    // Handle error
  }
}

Promise basics

  • 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.

Creating promises

  • The function passed to a new Promise 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.

// Resolving with a value, rejecting with an error new Promise((resolve, reject) => { performOperation((err, val) => { if (err) reject(err); else resolve(val); }); });

// Resolving without value, no need for reject const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

Handling promises

  • Promise.prototype.then() accepts two optional arguments (onFulfilled, onRejected).

  • Promise.prototype.then() will call onFulfilled once the promise is fulfilled.

  • Promise.prototype.then() will call onRejected if the promise is rejected.

  • Promise.prototype.then() passes errors through if onRejected in undefined.

  • Promise.prototype.catch() accepts one argument (onRejected).

  • Promise.prototype.catch() behaves like Promise.prototype.then() when onFulfilled is omitted.

  • Promise.prototype.catch() passes fulfilled values through.

  • Promise.prototype.finally() accepts one argument (onFinally).

  • Promise.prototype.finally() calls onFinally with no arguments once any outcome is available.

  • Promise.prototype.finally() passes through input promise.

promisedOperation() .then( val => value + 1, // Called once the promise is fulfilled err => { // Called if the promise is rejected if (err === someKnownErr) return defaultVal; else throw err; } ) .catch( err => console.log(err); // Called if the promise is rejected ) .finally( () => console.log('Done'); // Called once any outcome is available );

  • All three of the above methods will not be executed at least until the next tick, even for promises that already have an outcome.

Combining promises

  • 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 ]) => { // Values always correspond to the order of promises, // not the order they resolved in (i.e. v1 corresponds to p1) });

Promise .race([ p1, p2, p3 ]) .then(val => { // val will take the value of the first resolved promise });

async/await

  • 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(); // Do stuff here } catch (err) { // Handle error } }

PreviousEC2 API toolsNextCHEATSHEET (3)

Last updated 3 years ago

Was this helpful?

πŸ“š