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) {
console.log(123);
return err;
}
}
return result;
};
const asyncTask1 = new Promise((resolve) => setTimeout(() => resolve('Task 1'), 1000));
const asyncTask2 = new Promise((resolve, reject) => setTimeout(() => reject('Error in Task 2'), 500));
const asyncTask3 = new Promise((resolve) => setTimeout(() => resolve('Task 3'), 1500));
(async () => {
try {
const results = await promiseAllAsyncAwait([asyncTask1, asyncTask2, asyncTask3]);
console.log(results);
} catch (error) {
console.error('Error in promiseAllAsync:', error);
}
})();
it should output 123 to the console, but it does not output. it just outputs this error '[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "Error in Task 2".] { code: 'ERR_UNHANDLED_REJECTION' }'
It looks like you are trying to re-implement
Promise.allusing onlyasync/await. That is not possible, since withawaityou can only wait for one promise after the other. However,Promise.allneeds to register a handler on all passed promises immediately, to be able to handle rejections as soon as possible (by forwarding the error and rejecting the returned promise).Your code would eventually output
123, but the unhandled promise rejection (asyncTask2is rejected before your code wouldawaitit) crashes your nodejs process.