SHARE
TWEET

Untitled

a guest Aug 20th, 2019 64 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function promiseAll() {
  2.   if (!arguments.length) {
  3.     return Promise.resolve(null);
  4.   }
  5.   var args = arguments;
  6.   if (args.length === 1 && Array.isArray(args[0])) {
  7.     args = args[0];
  8.   }
  9.   var count = 1;
  10.   var total = args.length;
  11.   var result = [];
  12.   function resolveHandler(val, cb) {
  13.     result.push(val);
  14.     if (count === total) {
  15.       cb(result);
  16.     }
  17.     count++;
  18.   }
  19.   return new Promise(function(resolve, reject) {
  20.     for (var i = 0; i < total; i++) {
  21.       Promise.resolve(args[i])
  22.         .then(function(value) {
  23.           resolveHandler(value, resolve);
  24.         })
  25.         .catch(function(error) {
  26.           reject(error);
  27.         });
  28.     }
  29.   });
  30. }
  31.  // es-next-gen way using async await
  32. const promiseAllAsyncAwait = async function() {
  33.   if (!arguments.length) {
  34.     return null;
  35.   }
  36.   let args = arguments;
  37.   if (args.length === 1 && Array.isArray(args[0])) {
  38.     args = args[0];
  39.   }
  40.   const total = args.length;
  41.   const result = [];
  42.   for (let i = 0; i < total; i++) {
  43.     try {
  44.       const res = await Promise.resolve(args[i]);
  45.       if (res) {
  46.         result.push(res);
  47.       }
  48.     } catch (err) {
  49.       return err;
  50.     }
  51.   }
  52.   return result;
  53. };
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top