Coding Recipes
  • Introduction
  • Welcome
    • Introduction
  • SEO Recipes
    • How can I add more metadata to my page to improve SEO?
  • Console Recipes
    • How to colour text in the browser and server console
  • Array Recipes
    • How can I filter out falsey values?
  • Object Recipes
    • How can I clone an object?
    • How can I destructure an object?
    • How can I pretty-print an object?
    • How can I conditionally add a key-value into an object?
    • How can I pull keys, values and entries off an object?
    • How can I build an object with computed property names?
    • What does 'this' mean?
    • How does inheritance work between objects?
    • How can I build a query string from an object?
    • How to instantiate a class using an object of that class?
    • Nested Ternaries vs Switch Statements
  • String Recipes
    • How can I tokenise a string of values into an array?
    • How can I parse a template string into its constant and variable parts?
  • Function Recipes
    • How to find out where your function is being called from
    • How can I simplify argument validation in a function?
    • How would I handle errors?
    • What types of functions can I rebind 'this' on?
    • How can I find out the length of a function's parameter list?
  • Asynchronous Recipes
    • How do I use fetch?
    • How do I use Promises?
    • How do I use async and await?
    • How do I use jQuery to make async calls?
    • How can I use Axios to make async calls?
    • How can I use Web Workers to achieve parallelism?
  • React Recipes
    • How can I DRY-up passing props to a React component?
    • How can I conditionally render JSX?
    • What are the different types of PropTypes I can use?
    • How can I handle a component throwing an uncaught exception?
    • How can I use context to selectively pass data down a component hierarchy? (2 approaches)
    • How to define a Higher Order Component (HOC) in React
    • What are the different lifecycle methods in React?
    • HOCs vs. RenderProps - How To Share State
    • How to use refs in React (3 Approaches)
  • React Router Recipes
    • How do I install react router 4 as an application dependency
    • What are the different types of routes that I can create?
    • How can I navigate between different types of routes?
    • How can I style the link for the route that is currently active?
    • How can I pass parameters to my routes?
    • How can I match routes by making sure parameters match a specific format?
    • How can I parse query parameters from a route?
    • How can I define a default catch-all route?
    • How can I render multiple components for a single route?
    • How can I create nested routes?
    • How can I redirect from one route to another route?
    • How can I intercept transitioning from one route to another route?
  • Conditional Logic Recipes
    • How can I avoid using multiple if..else if...else if style code?
    • How can I check which of several booleans is true?
  • RxJS Recipes
    • How can I subscribe to a series of numbers?
    • How can I subscribe to an array of numbers?
    • How can I transform an array of numbers?
    • How can I listen to double-click events?
    • How can I create an Observable from something else?
  • Redux Recipes
    • Redux - Architecture
    • React-Redux - Architecture
    • How to define custom middleware for Redux
    • How to enable Hot Module Reloading for a React-Redux-Webpack application
  • GraphQL
    • How can I create a simple GraphQL client and server?
    • Stuff
Powered by GitBook
On this page

Was this helpful?

  1. Asynchronous Recipes

How do I use Promises?

// Case 1: If a promise is resolved the THEN block is run
Promise.resolve(1)
  .then(value => console.log(`[case1] pass: ${value}`))
  .catch(error => console.log(`[case1] fail: ${error}`))

// Case 2: If a promise is rejected the CATCH block is run
Promise.reject(1)
  .then(value => console.log(`[case2] pass: ${value}`))
  .catch(error => console.log(`[case2] fail: ${error}`))

// Case 3: If all promises are resolved the THEN block is run
Promise.all([Promise.resolve(1), Promise.resolve(2)])
  .then(items => console.log(`[case3] pass: ${JSON.stringify(items)}`))
  .catch(error => console.log(`[case3] fail: ${error.toString()}`))

// Case 4: If all promises are rejected the CATCH block is run
Promise.all([Promise.reject(1), Promise.reject(2)])
  .then(items => console.log(`[case4] pass: ${JSON.stringify(items)}`))
  .catch(error => console.log(`[case4] fail: ${error.toString()}`))

// Case 5: If some promises are resolved and some are rejected the CATCH block is run
Promise.all([Promise.resolve(1), Promise.reject(2)])
  .then(items => console.log(`[case5] pass: ${JSON.stringify(items)}`))
  .catch(error => console.log(`[case5] fail: ${error.toString()}`))

// Case 6: If a chain of promises are all resolved the final THEN block is run
Promise.resolve(1)
  .then(data => Promise.resolve(data + 1))
  .then(data => Promise.resolve(data + 1))
  .then(data => Promise.resolve(data + 1))
  .then(data => console.log(`[case6] pass: ${JSON.stringify(data)}`))
  .catch(error => console.log(`[case6] fail: ${error.toString()}`))

// Case 7: If a chain of promises do not all resolve the CATCH block is run
Promise.resolve(1)
  .then(data => Promise.resolve(data + 1))
  .then(data => Promise.reject(data + 1))
  .then(data => Promise.resolve(data + 1))
  .then(data => console.log(`[case7] pass: ${JSON.stringify(data)}`))
  .catch(error => console.log(`[case7] fail: ${error.toString()}`))

// Case 8: How to avoid fail fast behaviour of Promise.all()
const request = async (data) => {
  try {
    if (data % 2 !== 0) throw new Error(`${data} not even`)
    return Promise.resolve({ value: data, valid: true })
  } catch (error) {
    return Promise.resolve({ value: error.toString(), valid: false })
  }
}

Promise
  .all([request(2), request(5), request(8)])
  .then(results => results.filter(({ valid }) => valid))
  .then(answers => console.log(answers))
PreviousHow do I use fetch?NextHow do I use async and await?

Last updated 5 years ago

Was this helpful?