Skip to content

Instantly share code, notes, and snippets.

@Saya47
Forked from priteshjha4u/promiseAll.js
Created April 17, 2024 18:44
Show Gist options
  • Save Saya47/3b505b07372d613e12622087c4197751 to your computer and use it in GitHub Desktop.
Save Saya47/3b505b07372d613e12622087c4197751 to your computer and use it in GitHub Desktop.
Promise.all implementation in vanilla JavaScript
function promiseAll() {
if (!arguments.length) {
return Promise.resolve(null);
}
var args = arguments;
if (args.length === 1 && Array.isArray(args[0])) {
args = args[0];
}
var count = 1;
var total = args.length;
var result = [];
function resolveHandler(val, cb) {
result.push(val);
if (count === total) {
cb(result);
}
count++;
}
return new Promise(function(resolve, reject) {
for (var i = 0; i < total; i++) {
Promise.resolve(args[i])
.then(function(value) {
resolveHandler(value, resolve);
})
.catch(function(error) {
reject(error);
});
}
});
}
// es-next-gen way using async await
const promiseAllAsyncAwait = async function() {
if (!arguments.length) {
return null;
}
let args = arguments;
if (args.length === 1 && Array.isArray(args[0])) {
args = args[0];
}
const total = args.length;
const result = [];
for (let i = 0; i < total; i++) {
try {
const res = await Promise.resolve(args[i]);
if (res) {
result.push(res);
}
} catch (err) {
return err;
}
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment