Created
July 25, 2022 03:57
-
-
Save semlinker/da55fbf83b4375834a5d103bc2dbccf7 to your computer and use it in GitHub Desktop.
Promise.all
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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