Poppy Cooke

Poppy Cooke


JS Promises: race vs all vs allSettled

In this JavaScript promises tutorial, we are going to go over promises and three different promise methods that you can use when writing JavaScript or Node code.

Introduction – 00:00
Promise.all() – 01:33
Promise.allSettled() – 07:27
Promise.race() – 11:06

Promises have been around for a while now, but up until ES6, we were forced to use them through a third-party library, and the implementations and APIs varied a bit from one another. Thankfully, ES6 came and standardized the API by implementing a native Promise object, allowing everyone to ditch the third-party implementations.

That being said, maybe you were like me and because it required a third-party library, you were ignoring promises and relying on callbacks and libraries such as async.js to deal with that code and avoid running into callback hell (or the pyramid of doom as it is also known).

But now that promises are a native construct, there is really no excuse to ignore them anymore. So in this article, I want to cover three methods that’ll help you deal with some more complex use cases while also dealing with multiple promises at once.

But first, I want to cover one of the main benefits that the promise-based syntax brings to the table.

Declarative programming

Through the process of using the method chaining syntax, and the logic behind the method names (i.e then and catch), one can construct a block of code that focuses on declaring the intent for it. Instead of actually specifying how it needs to do what we need.

Let me explain. What if you wanted to grab every number inside a list and double it? How would you go about it?

The way we usually learn to write that code is to think like the computer:

You need to iterate over every item in the list, so you’ll need a position counter, which needs to go from 0 to the amount of numbers in the array, and for every number, you need to double it, and possibly add it into another different array.

Which translates to:

let list = [1,2,3,4,5];
let results = []
for(let counter = 0; counter < list.length; counter++) {
       results[i] = list[i] * 2;

Now, what I propose is to instead, think about what needs to happen and write that. In other words:

Map every number to its double.

let list = [1,2,3,4,5];
let results = list.map( i => i * 2 );


This is a very simple example, but it shows the power behind Declarative Programming.

A simple change in your approach can help you write cleaner, easier to read code. The cognitive load behind reading the second example is considerably lower than the first one since when using the for loop, you have to mentally parse the code and execute it line by line, while the map is something you can quickly interpret at a higher level.

Another benefit of writing code this way is you start thinking about transformations, or steps, that your data needs to go through.

Let me show you:

authenticateUser(usrname, pwd, (err, isAuth) => {
    if(err) return dealWithYourErrors(err);
    if(!isAuth) return dealWithUnauthorizedAccess(usrname);
    getSessionToken(usrname, (err, token) => {
        if(err) return dealWithYourErrors(err);
        loadUserDetails(usrname, (err, details) => {
            if(err) retun dealWithYourErrors(err);
            let user = new User(usrname, token, details);
            performAction(user, (err, result) => { //this is what you wanted to do all along
                if(err) return dealWithYourErrors(err);

The above is a classic example of nested callbacks, where you have several pieces of information that need to be taken from different services (or in different steps due to some other logic).

By default, callbacks only let you deal with asynchronous behavior serially, which, in this case, is not ideal. Both getSessionToken and loadUserDetails could be done in parallel since they don’t require the results of each other to perform their operations.

Sadly, doing it would require some extra code, such as using async.js or writing your own logic.

Furthermore, the code’s entire structure is imperative in the sense that it’s explicitly stating how to deal with errors and how to deal with serial calls. You (the developer working on this) need to think about these steps while writing them to ensure the correct behavior.

Let me show you how a promise-based approach would be written:

authenticateUser(username, pwd)
    .then( preActions )
    .then( performAction )

I’m sure we can all agree that is a lot simpler to write and to read. Let me show you a mocked implementation of these functions since promises need to be returned in all of them:

function authenticateUser(usr, pwd){ //main function called by the developer
    return new Promise( (resolve, reject) => {
        //auth logic goes here...
        resolve(usr); //assuming usr and pwd are valid...
/** once logged in, we'll need to get the session token and load the user's details
function preActions(usrname) { 
    return Promise.all([getSessionToken(usrname), loadUserDetails(usrname)]);

function getSessionToken(usrname) {
    return new Promise( (resolve, reject) => {
        //logic for getting the session token
function loadUserDetails(usrname) {
    return new Promise( (resolve, reject) => {
        //here is where you'd add the logic for getting the user's details
        resolve({name: 'Fernando'});
function performAction() {
    //the actual action: we're just logging into stdout the arguments recevied
function dealWithYourErrors(err) {

Here are the highlights from the above code:

  • preActions calls both functions in parallel, using the all method for the native Promise object. If any of them were to fail (thus rejecting their respective promise), then the entire set would fail and the catch method would’ve been called
  • The others are simply returning the promises

The above example is the perfect transition into the first method I want to cover: all.

The Promise.all method

Perfect for when you’re having to deal with multiple, parallel, asynchronous calls, the all method allows you to have your cake and eat it too.

By definition,Promise.all will run all your promises until one of the following conditions are met:

  • All of them resolve, which would, in turn, resolve the promise returned by the method
  • One of them fail, which would immediately reject the promise returned

The thing to remember with Promise.all is that last bullet point: you can’t handle partial failures. If one of the promises is rejected, then the entire process is halted and the failure callback is called. This is not ideal if the rejected promise is not doing something mission-critical and its content could potentially be missing.

Think about a search service, that is getting the data from the main database, and using external services to enrich the results. These external services aren’t required and they’re just there to help you provide more information, if available.

Having these third-party services fail, during the search process would cause this method to fail, halting the search process and preventing from returning a valid search result to your user.

It is here, where you want your internal logic to allow all your promises to be executed, ignoring possible rejections along the way.

Enter Promise.allSettled

This is the solution to all your problems if you’re coming from a use case like the ones above. Sadly, this method is not yet part of the JavaScript. Let me explain: it is a proposed addition that is being considered and reviewed. But sadly, is not a native part of the language just yet.

That being said, given the number of external implementations out there, I thought about covering it anyways.

The gist of it is that unlike the previous method, this one will not fail once the first promise is rejected, instead, it’ll return a list of values. These values will be objects, with two properties:

  1. The status of the returned promised (either ‘rejected’ or ‘fulfilled’)
  2. The value of the fulfilled promise or the reason the in case of a rejected promise
var allSettled = require('promise.allsettled');
var resolved = Promise.resolve(42);
var rejected = Promise.reject(-1);
allSettled([resolved, rejected]).then(function (results) {
    assert.deepEqual(results, [
        { status: 'fulfilled', value: 42 },
        { status: 'rejected', reason: -1 }
allSettled.shim(); // will be a no-op if not needed
Promise.allSettled([resolved, rejected]).then(function (results) {
    assert.deepEqual(results, [
        { status: 'fulfilled', value: 42 },
        { status: 'rejected', reason: -1 }

The above example shows the implementation running, it’s a third-party library promise.allsettled mind you, but it complies with the latest version of the Spec.

Note: Don’t let the name of the method confuse you, many people think “allSettled” means the same as “allResolved”, which is not correct. A promise is settled once it gets either resolved or rejected, otherwise, it’s pending. Check out the full list of states and fates a Promise can have for more details.

What if you wanted to stop at the first resolved promise?

What if instead of stopping once the first promise fails (much like Promise.all does) you wanted to stop once the first one resolves.

This is the other way that the Promise object allows you to deal with multiple promises, by using the race method, which, instead of trying to resolve all promises, actually just waits for the first one to finish, and either fails or succeeds based on whether the promise was resolved or rejected.

Yeah, I kind of cheated a bit there with the title, because this method will also stop the process if the first thing to happen is a rejected promise (just like Promise.all).

But pay no attention to that, let’s think about why you’d want to have several promises running in parallel and only take the result from the first one that gets settled.

When do you use race?

There are, believe or not, several examples of why you’d want to use this method. Let me give you two for now:

Número 1: Performance checks

If, for instance, performance was an important part of your platform, you might want to have several copies of the data source and you could try to query them all hoping to get the fastest one, depending on network traffic or other external factors.

You could do it without promises, but again, there would be an added expense to this approach, since you would have to deal with the logic to understand who returned first and what to do with the other pending requests.

With promises and the race method, you can simply focus on getting the data from all your sources and let JavaScript deal with the rest.

const request = require("request");

let sources = ["http://www.bing.com", "http://www.yahoo.com", "http://www.google.com" ];

let checks = sources.map( s => {
  return new Promise( (res, rej) => {
    let start = (new Date()).getTime()
    request.get(s, (err, resp) => {
        let end = (new Date()).getTime()
        if(err) return rej(err)
            datasource: s,
            time: end - start

Promise.race(checks).then( r => {
  console.log("Fastest source: ", r.datasource, " resolved in: ", r.time, " ms")

Yes, the code is a bit basic, and there are probably many ways for you to improve it, but it shows my point. I’m checking which data source is fastest for me without having to add any particular logic to deal with asynchronous resolutions. If I wanted to compare results, I would have to change this for a Promise.allSettled call instead.

Number 2: Loading indicator, should I show it?

Another example where you might want to consider using this method is when trying to decide whether or not to display a loading indicator in your UI. A good rule of thumb when creating SPAs is that your asynchronous calls should trigger a loading indicator for the user, to let them know something is happening.

But this rule is not ideal when the underlying request happens very quickly, because all you’ll probably get in your UI is a flicker of a message, something that goes by too fast. And loading times might depend on too many things for you to create a rule to know when to show the indicator, and when to simply do the request without it.

You can play around with the concepts of rejection and resolution to have something like this:

function yourAsynchronousRequest(params) {
  return new Promise((resolve, reject) => {
       //here is your request code, it'll resolve once it gets the actual data from the server

function showDataToUser(params) {
  return yourAsynchronousRequest(params).then( data => console.log("data fetched:", data));

function timeout() {
  return new Promise((resolve, reject) => {
    setTimeout(() => reject(), TIMEOUTLIMIT); //TIMEOUTLIMIT is a constant you configured

function showLoadingIndicator() {
  console.log("please wait...")

Promise.race([showDataToUser(), timeout()]).catch(showLoadingIndicator);

Now the race is against an actual asynchronous request and a timeout set as a limiter. Now the logic to decide whether to show or not the loading indicator is hidden behind the race method.

Final thoughts

Promises are fun, and ignoring them was not one of my best moves back in the day, so I’m super glad I’ve decided to incorporate them into my daily coding habits, and if you haven’t yet, I strongly suggest you do it as well.

Let me know in the comments if you’re using these methods, and I’m especially interested in what kind of use cases you have for the Promise.race method, I really want to know!

See you on the next one!

#javascript #es6 #node-js #web-development

What is GEEK

Buddha Community

JS Promises: race vs all vs allSettled

NBB: Ad-hoc CLJS Scripting on Node.js


Not babashka. Node.js babashka!?

Ad-hoc CLJS scripting on Node.js.


Experimental. Please report issues here.

Goals and features

Nbb's main goal is to make it easy to get started with ad hoc CLJS scripting on Node.js.

Additional goals and features are:

  • Fast startup without relying on a custom version of Node.js.
  • Small artifact (current size is around 1.2MB).
  • First class macros.
  • Support building small TUI apps using Reagent.
  • Complement babashka with libraries from the Node.js ecosystem.


Nbb requires Node.js v12 or newer.

How does this tool work?

CLJS code is evaluated through SCI, the same interpreter that powers babashka. Because SCI works with advanced compilation, the bundle size, especially when combined with other dependencies, is smaller than what you get with self-hosted CLJS. That makes startup faster. The trade-off is that execution is less performant and that only a subset of CLJS is available (e.g. no deftype, yet).


Install nbb from NPM:

$ npm install nbb -g

Omit -g for a local install.

Try out an expression:

$ nbb -e '(+ 1 2 3)'

And then install some other NPM libraries to use in the script. E.g.:

$ npm install csv-parse shelljs zx

Create a script which uses the NPM libraries:

(ns script
  (:require ["csv-parse/lib/sync$default" :as csv-parse]
            ["fs" :as fs]
            ["path" :as path]
            ["shelljs$default" :as sh]
            ["term-size$default" :as term-size]
            ["zx$default" :as zx]
            ["zx$fs" :as zxfs]
            [nbb.core :refer [*file*]]))

(prn (path/resolve "."))

(prn (term-size))

(println (count (str (fs/readFileSync *file*))))

(prn (sh/ls "."))

(prn (csv-parse "foo,bar"))

(prn (zxfs/existsSync *file*))

(zx/$ #js ["ls"])

Call the script:

$ nbb script.cljs
#js {:columns 216, :rows 47}
#js ["node_modules" "package-lock.json" "package.json" "script.cljs"]
#js [#js ["foo" "bar"]]
$ ls


Nbb has first class support for macros: you can define them right inside your .cljs file, like you are used to from JVM Clojure. Consider the plet macro to make working with promises more palatable:

(defmacro plet
  [bindings & body]
  (let [binding-pairs (reverse (partition 2 bindings))
        body (cons 'do body)]
    (reduce (fn [body [sym expr]]
              (let [expr (list '.resolve 'js/Promise expr)]
                (list '.then expr (list 'clojure.core/fn (vector sym)

Using this macro we can look async code more like sync code. Consider this puppeteer example:

(-> (.launch puppeteer)
      (.then (fn [browser]
               (-> (.newPage browser)
                   (.then (fn [page]
                            (-> (.goto page "https://clojure.org")
                                (.then #(.screenshot page #js{:path "screenshot.png"}))
                                (.catch #(js/console.log %))
                                (.then #(.close browser)))))))))

Using plet this becomes:

(plet [browser (.launch puppeteer)
       page (.newPage browser)
       _ (.goto page "https://clojure.org")
       _ (-> (.screenshot page #js{:path "screenshot.png"})
             (.catch #(js/console.log %)))]
      (.close browser))

See the puppeteer example for the full code.

Since v0.0.36, nbb includes promesa which is a library to deal with promises. The above plet macro is similar to promesa.core/let.

Startup time

$ time nbb -e '(+ 1 2 3)'
nbb -e '(+ 1 2 3)'   0.17s  user 0.02s system 109% cpu 0.168 total

The baseline startup time for a script is about 170ms seconds on my laptop. When invoked via npx this adds another 300ms or so, so for faster startup, either use a globally installed nbb or use $(npm bin)/nbb script.cljs to bypass npx.


NPM dependencies

Nbb does not depend on any NPM dependencies. All NPM libraries loaded by a script are resolved relative to that script. When using the Reagent module, React is resolved in the same way as any other NPM library.


To load .cljs files from local paths or dependencies, you can use the --classpath argument. The current dir is added to the classpath automatically. So if there is a file foo/bar.cljs relative to your current dir, then you can load it via (:require [foo.bar :as fb]). Note that nbb uses the same naming conventions for namespaces and directories as other Clojure tools: foo-bar in the namespace name becomes foo_bar in the directory name.

To load dependencies from the Clojure ecosystem, you can use the Clojure CLI or babashka to download them and produce a classpath:

$ classpath="$(clojure -A:nbb -Spath -Sdeps '{:aliases {:nbb {:replace-deps {com.github.seancorfield/honeysql {:git/tag "v2.0.0-rc5" :git/sha "01c3a55"}}}}}')"

and then feed it to the --classpath argument:

$ nbb --classpath "$classpath" -e "(require '[honey.sql :as sql]) (sql/format {:select :foo :from :bar :where [:= :baz 2]})"
["SELECT foo FROM bar WHERE baz = ?" 2]

Currently nbb only reads from directories, not jar files, so you are encouraged to use git libs. Support for .jar files will be added later.

Current file

The name of the file that is currently being executed is available via nbb.core/*file* or on the metadata of vars:

(ns foo
  (:require [nbb.core :refer [*file*]]))

(prn *file*) ;; "/private/tmp/foo.cljs"

(defn f [])
(prn (:file (meta #'f))) ;; "/private/tmp/foo.cljs"


Nbb includes reagent.core which will be lazily loaded when required. You can use this together with ink to create a TUI application:

$ npm install ink


(ns ink-demo
  (:require ["ink" :refer [render Text]]
            [reagent.core :as r]))

(defonce state (r/atom 0))

(doseq [n (range 1 11)]
  (js/setTimeout #(swap! state inc) (* n 500)))

(defn hello []
  [:> Text {:color "green"} "Hello, world! " @state])

(render (r/as-element [hello]))


Working with callbacks and promises can become tedious. Since nbb v0.0.36 the promesa.core namespace is included with the let and do! macros. An example:

(ns prom
  (:require [promesa.core :as p]))

(defn sleep [ms]
   (fn [resolve _]
     (js/setTimeout resolve ms))))

(defn do-stuff
   (println "Doing stuff which takes a while")
   (sleep 1000)

(p/let [a (do-stuff)
        b (inc a)
        c (do-stuff)
        d (+ b c)]
  (prn d))
$ nbb prom.cljs
Doing stuff which takes a while
Doing stuff which takes a while

Also see API docs.


Since nbb v0.0.75 applied-science/js-interop is available:

(ns example
  (:require [applied-science.js-interop :as j]))

(def o (j/lit {:a 1 :b 2 :c {:d 1}}))

(prn (j/select-keys o [:a :b])) ;; #js {:a 1, :b 2}
(prn (j/get-in o [:c :d])) ;; 1

Most of this library is supported in nbb, except the following:

  • destructuring using :syms
  • property access using .-x notation. In nbb, you must use keywords.

See the example of what is currently supported.


See the examples directory for small examples.

Also check out these projects built with nbb:


See API documentation.

Migrating to shadow-cljs

See this gist on how to convert an nbb script or project to shadow-cljs.



  • babashka >= 0.4.0
  • Clojure CLI >=
  • Node.js 16.5.0 (lower version may work, but this is the one I used to build)

To build:

  • Clone and cd into this repo
  • bb release

Run bb tasks for more project-related tasks.

Download Details:
Author: borkdude
Download Link: Download The Source Code
Official Website: https://github.com/borkdude/nbb 
License: EPL-1.0

#node #javascript

Promise.allSettled() vs Promise.all()

Promise.allSetlled() is recently introduced in ECMA 2020.
Check out how it is different from Promise.all()


#javascript #promise.all #promise.allsettled #ecma #promise #jquery

Node Js Vs. React Js: Difference Between Node JS and React JS

The Js at the end of both Node and React refer to the language of JavaScript. Node and React are both the frameworks of  JavaScript. However, the ensuing language that both the frameworks have been the same, the use cases for both of these frameworks. However, they are totally different.

Some people might even argue that to find the difference between node js and react js is just like comparing a train to an airplane. Both of them work on an entirely different domain. The main reason why Node and React’s comparison is unfair is that Node.js is a framework to handle back-end, meaning it is developed to handle the server-side computations.

Meanwhile, React.js was developed to handle the User Interface and User Experience (UI/UX). Although glaringly present, the differences do not take anything away from the sheer power and the versatility that each of these frameworks brings into their respective domain. Another way to string together the main difference would be that neither Node.js or React.js are interchangeable at any stage of your web development project.

With that being said, there are individual minute differences that any developer should consider when working on their projects, such as the performance, the learning curve, the community of both the frameworks and microservices’ support. Listed below, you will find a comprehensive weighted comparison of node js vs. react js on the aforementioned grounds. But before we begin our comparison, we must first understand both Node.js and React.js intricately and discuss the various use cases of these technologies.

Read:  Difference between NodeJS and Django


What exactly is the Node.js JavaScript framework?

The need for a robust means to handle the backend, server-side development yielded the framework we know as Node.js. Node.js was developed by Google and is based out of their V8 engine present in their web browser, i.e., Google Chrome. Node.js is a lightweight framework mainly because of its event-driven nature and the fact that it does not block the I/O. Node.js really shines the brightest when used to host API’s, access the database for the website, and serve the HyperText Transfer Protocol.

Who are the people making use of Node.js?

Node.js enjoys a very diverse clientele, with major players like Netflix, Uber, and Trello, all making use of Node.js in their backend. The reason why each of these companies uses this framework is different. Netflix, the leading online content streaming service, has to conduct A/B testing; only then would they serve the 93 million active users of their streaming service. The lightweight nature of Node.js has allowed them to serve the content swiftly. They have both reduced their startup time by over 70% and improved their scalability by shifting to Node.js.

#node js #node js vs react js #react js

sophia tondon

sophia tondon


Angular.JS vs Node.JS || Find the best for your project - Valuecoders

Whether MNCs or Startups, many companies use Angular.JS or Node.JS to develop web applications as these are among the best JavaScript frameworks used for web applications.

According to Statista, Node.JS and Angular.JS are the best frameworks used by developers, with 51.4% and 25.1%, respectively.

Both these frameworks have unique features and advantages, which makes them preferred over the other frameworks.

Many enterprises use these frameworks without even understanding their uniqueness and the type of projects they are suited or made, which is why, today, I will compare some of the best features and advantages of these two frameworks.

So, let’s dive into and learn various things about Angular.JS vs Node.JS without any further delay.


AngularJS is a fundamental framework for robust web apps. It makes you use HTML as your template language and allows you to spread HTML’s syntax to clearly and succinctly express your application’s components.

AngularJS’s dependency injection & data binding eliminate much of the code you would otherwise have to write. And it all happens within the browser, making it a perfect partner with any server technology.

AngularJS is what HTML would have been having it been designed for applications. HTML is a great declarative language for static documents. It does not contain much in creating applications.

Let’s discuss some main features of Angular.JS and its advantages:

Data Binding

Data binding is probably the most impressive and helpful feature of AngularJS. It will save you from writing a considerable amount of repetitive code.

A typical web application can contain up to 80% of its codebase, dedicated to traversing, manipulating, and listening to the DOM. Data binding makes this code escape so you can concentrate more on your application. Think of your Model as the only source of truth for your application. Your model is where you go to read or update anything in your application.

Data binding directives provide a projection of your Model to the application’s view. This projection is perfect and occurs without any effort on your part.


Another great feature of AngularJS is the fact that it uses the HTML language to build UI. The HTML language is a general and declarative language with concise tags that are easy to understand.

This leads to a more systematic and straightforward UI. JavaScript interfaces are usually more challenging to organize and develop. If you’re looking for a solution that’s fast, easy, and simple to use at a moment’s notice, then this could be it.

Model View Controller (MVC)

MVC is a software design pattern for developing web applications. It is made up of:

Directives allow angular to provide additional functionality with the HTML language. Directives can also be used to “decorate” components with behavior and manipulate DOM attributes in interesting ways. The controller does not need to control the DOM directly, as this must be done through directives.

Directives are a separate part of the set of elements that can be used anywhere other than a web application. The directives provide developers with the element-rich HTML they need to strengthen their online presence.

If you are looking to hire a dedicated angular developer, you can hire an angular js development company.

Node.js is a free and open-source server environment that runs on various platforms(Windows, Linux, Unix, Mac, OS X, etc.). Node.js uses JavaScript on the server.

Node.js is preferred because of its rich library of several JavaScript modules that helps in simplifying web development to a greater extent. Many companies hire Node.js developers for making a NodeJS web application development as it possesses many features.

Read More - https://www.valuecoders.com/blog/technology-and-apps/angular-js-vs-node-js-find-the-best-for-your-project/

#hire nodejs developer #node js development services #hire node js developer #hiring node js developers #hire node js developers #hire dedicated angular js developer

Javascript Promise Race Example | Promise.race() Tutorial

Javascript Promise race() is an inbuilt function that returns the promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects, with the value or reason from that promise. If the iterable passed is empty, the promise returned will be forever pending.

If the iterable contains one or more non-promise value and an already resolved/rejected promise, then Promise.race() method will resolve to the first of these values found in the iterable.

Javascript Promise Race

The syntax for Javascript Promise.race() method is following.


An iterable parameter is an object, such as an array.

The Javascript Promise Race Example is the following.

// app.js

const p1 = Promise.resolve(21);
const p2 = new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars
    setTimeout(() => {
    }, 1000);

Promise.race([p1, p2]).then(values => { 

In the above example, the p1 promise is resolved synchronously whereas p2 promise resolved asynchronously. So, when the Promise.race() function is start executing, the race between p1 and p2 promise has also been started and whichever resolves first, it will return in the output.

#javascript #promise.race #js