working on it ...

Filters

Explore Public Snippets

Sort by

Found 39 snippets matching: promise.all

    public by slavka1979 modified May 26, 2017  211  1  5  0

    Promise.all for Rejections and Resolves

    Always call then, even when one promise rejects
    // https://davidwalsh.name/promises-results
    Promise.all([
        // Resolves
        Promise.resolve(1), 
        // Rejects after 2 seconds
        new Promise((resolve, reject) => setTimeout(() => reject(1), 2000))
    ].map(p => p.catch(() => undefined))).then(() => console.log('done!'));

    external by Austin Wood modified Nov 23, 2016  45  0  1  0

    Recreating Promise.all with async/await

    Recreating Promise.all with async/await: promise-dot-all.js
    /* 
    
     Let us re-create Promise.all
    
     Promise.all method returns a promise that resolves when all of the promises in the iterable argument have resolved, 
     or rejects with the reason of the first passed promise that rejects.
     
     Read more about Promise.all on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
     
     A basic example would be something like this:
     
     Promise.all([promise1, promise2, promise3])
       .then(allResolvedData => console.log('here are the resolutions to the promises', allResolvedData))
       
     */
    
    const allAsync = (...listOfPromises) => {
        return new Promise(async (resolve, reject) => {
            let results = []
            for (let promise of listOfPromises) {
                results.push(await promise.then(async resolvedData => await resolvedData))
                if (results.length === listOfPromises.length) resolve(results)
            }
        })
    }
    
    const promise1 = Promise.resolve('first')
    const promise2 = new Promise((resolve, reject) => setTimeout(resolve, 1000, 'second'))
    const promise3 = Promise.resolve('third')
    
    allAsync(promise1, promise2, promise3)
        .then(resolvedData => {
            console.log(resolvedData) // ['first', 'second', 'third']
        })
    
    

    external by Alex Schmidt modified Oct 3, 2016  45  0  1  0

    Inverse of ES6 Promise.all

    Inverse of ES6 Promise.all: Inverse of Promise.all()
    // Inspired by Jordan Harband(https://github.com/ljharb)
    
    let user1 = { role: 'A'};
    let user2 = { role: 'B'};
    let user3 = { role: 'C'};
    
    const checkA = x => {
      return new Promise ( function (resolve, reject) {
          if (x.role === 'A') {
            return resolve("CheckA resolved");
          } else {
            return reject("CheckA rejected");
          }
      });
    };
    
    const checkB = x => {
      return new Promise ( function (resolve, reject) {
          if (x.role === 'B') {
            return resolve("CheckB resolved");
          } else {
            return reject("CheckB rejected");
          }
      });
    };
    
    
    function antiAll(promises) { 
      const thrower = x => { throw x; }; 
      const identity = x => x; 
      return Promise.all(promises.map(x => x.then(thrower, identity)))
        .then(thrower, identity); 
    }
    antiAll([checkA(user1), checkB(user1)])
    .then((res) => {
      console.log(res);
    })
    .catch( (err) => {
      console.log(err);
    });
    
    

    external by dannyrscott modified Jul 22, 2014  34  0  1  0

    Promise.all fancy

    Promise.all fancy: gistfile1.js
    Promise.all([
    	aPromiseFunc(),
    	aSyncFunc(),
    	7,
    	x.data ? anAsync(x.data) : null
    ])
    .spread(aProm, aSync, num, anAsync) {
    	//aProm is resolve of aPromiseFunc
    	//aSync is return of aSyncFunc
    	//num === 7
    	// anAsync === resolve of anAsync || null
    });
    
    

    external by Sibelius Seraphini modified Oct 6, 2016  22  0  1  0

    Promise.all limit

    Promise.all limit: promise.all.limit.js
    let start = 0;
    const limit = 10;
    
    items.slice(start, limit).forEach(subset =>
        await Promise.all(subset.map(async (item) => {
            // do async work with a single item
        }))
            .then(() => (start += limit)
    );
    
    

    external by Dejan Dimic modified Oct 2, 2016  22  0  1  0

    Promise.all reduce

    Promise.all reduce: Promise.all reduce.js
    Promise.all(objectsToProcess.reduce((sum, item) => {
      if (item && item.shouldProcess) {
        sum.push(asyncFunction(item));
      }
      return sum;
    }, []))
    .then(values => { console.log(values); })
    .catch(reason => { console.log(reason); });
    
    

    external by rubystream modified Oct 2, 2016  22  0  1  0

    Promise.all vanila

    Promise.all vanila: Promise.all vanila.js
    // objectsToProcess  - array of objects to process
    // asyncFunction - asynct function that take objectsToProcess item as argument and return a promise
    
    Promise.all(objectsToProcess.map(asyncFunction))
      .then(values => { console.log(values) })
      .catch(reason => { console.log(reason) });
    
    

    external by Jonathan Boston modified Jul 14, 2015  500  0  3  0

    Promise.all with core.async

    Promise.all with core.async: promise.cljs
    (ns cljs-made-easy.core
      (:refer-clojure :exclude [into])
      (:require-macros [cljs.core.async.macros :refer [go go-loop]])
      (:require [cljs.core.async :refer [<! >!] :as a]))
    
    (enable-console-print!)
    
    (defn resolving-promise [key t reject]
      (go
        (pr (str key " starting"))
        (<! (a/timeout t))
        (pr (str key " finished"))
        (str key " waited " t "ms")))
    
    (defn rejecting-promise [key t reject]
      (go
        (pr (str key " starting"))
        (<! (a/timeout t))
        (>! reject (str key " had an error after " t "ms"))
        "This string won't be used"))
    
    (defn into [coll & chans]
      (go-loop [coll coll
                chans chans]
        (if (seq chans)
          (recur (conj coll (<! (first chans)))
                 (rest chans))
          coll)))
    
    (defn all [reject & chans]
      (go
        (let [all-chans (apply into [] chans)
              [v ch] (a/alts! [reject all-chans])]
          (if (= ch reject)
            (pr (str "Rejected value: " v))
            (pr (str "Resolved values: " v))))))
    
    (defn demo-resolving []
      (let [reject (a/chan)]
        (go
          (<! (all reject
                   (resolving-promise :c1 2000 reject)
                   (resolving-promise :c2 1000 reject)
                   (resolving-promise :c3 1500 reject))))
        nil))
    
    (defn demo-rejecting []
      (let [reject (a/chan)]
        (go
          (<! (all reject
                   (resolving-promise :c1 2000 reject)
                   (resolving-promise :c2 1000 reject)
                   (rejecting-promise :c3 1500 reject))))
        nil))
    
    

    external by darthmall modified May 7, 2015  482  0  3  0

    Callbacks for Promise.all with and without lodash.spread

    Callbacks for Promise.all with and without lodash.spread: index.js
    // Without lodash
    
    function doSomething(results) {
      var fooResult = results[0];
      var barResult = results[1];
    }
    
    Promise.all([foo, bar]).then(doSomething);
    
    // With lodash
    
    function doSomething(fooResult, barResult) {
      
    }
    
    Promise.all([foo, bar]).then(_.spread(doSomething));
    
    

    external by Roy Ling modified Oct 9, 2016  357  0  3  0

    Promise.all in short

    Promise.all in short: promise.all.ts
    // inline type declaration for ES6 Promise object
    // see full at https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/es6-promise/es6-promise.d.ts
    declare class Promise {
        constructor(callback: (resolve: (value?: any) => void, reject: (reason?: any) => void) => void);
        then(onFulfilled?: (any) => any, onRejected?: (any) => any|void);
    }
    
    const isPromise: (p:any) => boolean = p => typeof p === 'object' && typeof p.then === 'function';
    
    const promiseAll: (promises:any[]) => Promise = promises => new Promise((resolve, reject) => {
        let results = [],
            pendingCount = promises.length,
            _resolve = (result, index) => {
                results[index] = result;
                if (--pendingCount === 0) {
                    console.log(`All resolved: ${results}`);
                    resolve(results);
                }
            };
        promises.forEach((promise, index) => {
            if (!isPromise(promise)) {
                console.log(`value at ${index} is not a promise, resolve to ${promise}`);
                _resolve(promise, index);
            } else {
                promise.then(result => {
                    console.log(`promise ${index} resolved to ${result}`);
                    _resolve(result, index);
                }, reject);
            }
        });
    });
    
    // test
    let promises:any[] = [
        0,
        new Promise(resolve => setTimeout(() => resolve(1), 2000)),
        new Promise(resolve => setTimeout(() => resolve(2), 1500))
    ];
    
    promiseAll(promises).then(results => console.log(results));
    
    
    
    • Public Snippets
    • Channels Snippets