Skip to content

Instantly share code, notes, and snippets.

@semlinker
Created July 25, 2022 03:57
Show Gist options
  • Save semlinker/da55fbf83b4375834a5d103bc2dbccf7 to your computer and use it in GitHub Desktop.
Save semlinker/da55fbf83b4375834a5d103bc2dbccf7 to your computer and use it in GitHub Desktop.
Promise.all
Promise.all = function (iterators) {
return new Promise((resolve, reject) => {
if (!iterators || iterators.length === 0) {
resolve([]);
} else {
// used to determine whether all tasks are completed
let count = 0;
let result = []; // result array
for (let i = 0; i < iterators.length; i++) {
// Considering that iterators[i] may be ordinary object,
// they are uniformly packaged as Promise object
Promise.resolve(iterators[i]).then(
(data) => {
// Save the corresponding results in order
result[i] = data;
// When all tasks are executed,
// return the result uniformly
if (++count === iterators.length) {
resolve(result);
}
},
(err) => {
// If any Promise object fails to execute,
// the reject() method is called
reject(err);
return;
}
);
}
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment