Sébastien Lucas / Dev wiki
  • Blog Wiki
  • Story book
  • Developers comics
  • Angular
    • Angular CLI + Angular.json
    • ngTemplateOutlet
    • Angular Schematic
    • Interceptor
    • Micro frontend + Mono repo
    • Build a library module
    • Error handling
    • Virtual and infinite scroll
    • Angular i18n
    • Debug Angular
    • Angular LifeCycle Hook
    • Nested forms in Angular
    • Angular Recipes
    • Master component in Angular
    • Perfomance optimization
    • Service Workers + PWA
    • Mobile
    • Electron app / Desktop app
    • Unit test & Angular
      • Unit test recipes (Jasmine / Karma / Angular)
      • Testing services with httpMock
    • Communication between components
    • Angular snippet library
    • Release and version management
    • Angular tutorial selection
    • UI components libraries
    • Angular libraries
    • Angular Tutorials
    • NGRX
      • Angular NGRX / Tips and code examples
      • Angular new Redux (alternative to ngrx)
      • NGRX unit test
      • Angular ngrx / Basics
    • Angular 2/Angular 1 differences
  • Graphql
  • Three.js
  • Ag grid
  • Open source BIM and 3D
  • Javascript
    • Null vs undefined
    • Html API
    • Await API
    • Debug memory leaks
    • Offline and PWA
    • Javascript tutorials
    • Javascript recipes
    • Bluebird missing docs
    • Alternative to lodash with ES6
    • ES6 syntax the best parts
    • Vanilla JS
  • RXJS
    • Docs
    • Recipes
    • Mock API and sandbox
    • Observables rxjs recipes
    • Combination operators
  • NODE.js
    • Environment variables
    • Fix CORS
    • Pagination requests in API
    • API tests
    • Node.js security
    • Learn node.js
    • Best libraries for node.js
    • Mongoose recipe
    • Debug node.js
  • Gatsby / React
    • Hooks
    • React concepts
    • Gatsby internationalisation
  • Ghost blog
  • Services for developers
    • SaaS images services
    • Airtable API examples
  • MISC
    • JIRA debugging
    • Wordpress plugins
    • Interview Sébastien Lucas
    • English expression
    • True recipes
    • Science podcast
  • AI
    • Machine learning open source
    • Tensor flow
    • Machine learning
    • Code examples
    • Courses and tutorials
    • Datasets
    • The Future of AI
    • Learn algo and data structures
  • Typescript
    • Generic types
    • Typescript recipes
    • Advanced types
      • Conditional types
      • Type guards
    • d.ts files
  • Docker
    • Starting with docker
    • Dockerise simple node app
    • Docker by aymen el amri
  • Mongodb
    • Pattern and data modeling
  • Devops
    • Heroku
    • Scaleway
    • Github template
    • Gitlab CI
    • http2
    • nginx
    • zsh
    • CI Continuous integration
    • DNS
    • Devops resources
    • Gcloud useful commands
    • Authenticate Gcloud
    • Documentation generators
    • Firebase database
  • Developers ressources
    • Online platform coding
      • Online courses
      • Coding games
      • Coding test platforms
      • Links to check
    • Good developers blogs
    • Nice open source project / github
  • Tooling
    • The chrome urls
    • Linux Mac tips
    • Webstorm configuration
    • Develop in Windows
    • Mac debug hardware
    • Mac Setup for a developer
    • Chrome extension
    • Develop toolbox
  • HTML / CSS
    • Tailwind
    • Css grid
    • ☘️Nice styles & generators
    • Favicon
    • Flexbox grid
    • Flexbox layout
    • PUG templates tips
    • Html and css references
    • Css snippets
    • SASS-CSS libraries
    • New things in scss
    • SASS best practices
    • Style lint
  • Tests
    • Cypress
      • Learn cypress and more tests
      • Cypress commands
      • Cypress plugins
      • Page object && app actions
      • Flaky tests
    • Mobile test
    • BDD + Cucumber
    • Puppeteer
    • Type of tests + Ressources
    • Jasmine test
    • Mock, fake, stub in unit tests
    • E2e tests with protactor
    • Mocha
  • REVIT & AEC tools
  • Git
    • Git commits
    • Git tips
    • Git hooks
    • Set up a mono repo
  • Design Pattern
    • Functional Programming
  • Job board / Remote jobs
  • SVG
  • JSON
  • Github
    • Forking a github repo
  • NPM
    • Private NPM packages
    • Publish to NPM with np
  • Yarn
    • Yarn evolution / 2, 3...
    • Yarn Linking
Powered by GitBook
On this page
  • Promise Concepts
  • 2 anti patterns not to fall in

Was this helpful?

  1. Javascript

Bluebird missing docs

PreviousJavascript recipesNextAlternative to lodash with ES6

Last updated 5 years ago

Was this helpful?

Blue bird is a great library of promise for front end (angular) and backend (node). But its documentation is definitely not good. Let's list and explain shorty the difference between each useful functions this library provide.

Promise Concepts

  • Sequential or Parallel processing

Sequential processing means each promises is processed one after the other. Could be useful if you want to have a control on the flow of processing. Or if you need the result of previous promise to process the next.

Parallel processing means the promises are processed at the same time. You cannot guaranty that the order will be preserved.

2 anti patterns not to fall in

  • Creating an explicit promise that wrap an already promise

  • then((success) => { }, error=> { })

    instead of

    ```js then(() => {

}) .catch(() => {

})

##  Useful bluebird function

* **Promise.all**
  - Params: Array of promise
  - Process in parallel
  - Reject early if an error occur
  - the return value is an array of each promises return in the order they were define

* **Promise.each**
  Same than promise.all but
  - Process in sequence

* **Promise.join**

It is recommended to use Promise.join instead or Promise.all
when the action to do are fixed  in advance and not numerous.
In this case only 3 promises that we know in advance.

```js
var Promise = require("bluebird");
var join = Promise.join;

join(getPictures(), getComments(), getTweets(),
    function(pictures, comments, tweets) {
    console.log("in total: " + pictures.length + comments.length + tweets.length);
});

The same that lodash _.some but with promises and with the count parameter that allow to tell the minimal promises that need to be fulfilled before

Example of the doc log only the 2 fastest server to respond.

Promise.some([
    ping("ns1.example.com"),
    ping("ns2.example.com"),
    ping("ns3.example.com"),
    ping("ns4.example.com")
], 2).spread(function(first, second) {
    console.log(first, second);
});

Use the properties of an object to define promise to be performed. The advantage is that the result is accessible with the same properties name that the input object. Giving the benefit of the spread() operator (instead of the then())

Promise.props({
    pictures: getPictures(),
    comments: getComments(),
    tweets: getTweets()
}).then(function(result) {
    console.log(result.tweets, result.pictures, result.comments);
});
Promise.all([
  /* Array of promises */

])
.then(() => {
  // To do when all promises array resolve
})
.catch(() => {
  // To do if any of the promise in the array had arrors
})
.finally(() => {
  // To do after the then() or catch() indepedantly of the Promise faith (success or errors)
})
 let arrayOfPromises = [
   promise1,
   promise2
 ];
  Promise.all(arrayOfPromises)
  .spread((returnOfPromise1, returnOfPromise2) =>  {
      console.log("return of promise1 " , returnOfPromise1);
      console.log("return of promise2 " , returnOfPromise1);
  });
  // Instead of
  Promise.all(arrayOfPromises)
  .then((result)  => {
      console.log("return of promise1 " , result[0]);
      console.log("return of promise2 " , result[2]);
  });

Allow doing something globally when error occurred

  // NOTE: event name is camelCase as per node convention
  process.on("unhandledRejection", function(reason, promise) {
      // See Promise.onPossiblyUnhandledRejection for parameter documentation
  });

  // NOTE: event name is camelCase as per node convention
  process.on("rejectionHandled", function(promise) {
      // See Promise.onUnhandledRejectionHandled for parameter documentation
  });

test if the promise is fulfilled

let mypromise = Promise.all()
// More code

timeout(500, () => {
  if (!mypromise.isFulfilled) {
    console.log('still not done')
  }
})

Cancel a promise if it has not been received already

The result of promise.all is an array of promises returns, but what if you want to define them as parameters ?

[isFullfilled]()

Blue bird documentation
http://bluebirdjs.com/docs/anti-patterns.html#the-explicit-construction-anti-pattern
http://bluebirdjs.com/docs/anti-patterns.html#the-explicit-construction-anti-pattern
Promise.some
Promise.props
finally()
cancel()
spread()
Global rejection error hook
http://bluebirdjs.com/docs/api/isfulfilled.html