Why does .catch () not catch reject () inside a Promise constructor in a loop on an async function if no error is passed?
Considering
(async () => {
const p = await new Promise((resolve, reject) => setTimeout(() => {
reject(new Error(1))
}, Math.floor(Math.random() * 1000))); return p})()
.then(data => console.log(data))
.catch(err => console.error(err));
Error()
recorded in .catch()
If we extend the template to use a loop, it Error
registers with.catch()
const fn = async(res, ...props) => {
for (let prop of props) res.push(await prop())
return res
}
const arr = [
() =>
new Promise((resolve, reject) =>
setTimeout(() =>
reject(new Error(1))
, Math.floor(Math.random() * 1000))
),
() =>
new Promise((resolve, reject) =>
setTimeout(() =>
resolve(1)
, Math.floor(Math.random() * 1000))
)
];
fn([], ...arr)
.then(data => console.log(data))
.catch(err => console.log(err));
If we use a loop to call several functions that return Promise
and do not explicitly pass Error()
to the reject()
Promise
constructor, the resolver
function .catch()
does not catch the error, and the array res
does not return, only the value Promise
passed to resolve()
is available in
const fn = async(res, ...props) => {
for (let prop of props) res.push(await prop())
return res
}
const arr = [
() =>
new Promise((resolve, reject) =>
setTimeout(() =>
reject(1)
, Math.floor(Math.random() * 1000))
),
() =>
new Promise((resolve, reject) =>
setTimeout(() =>
resolve(1)
, Math.floor(Math.random() * 1000))
)
];
fn([], ...arr)
// what happened to our array `res` returned from `fn`?
.then(data => console.log(data))
// what happened to our rejected Promise?
.catch(err => console.log(err));
Questions:
-
Why is
reject()
n't the call propagated to.catch()
whenError()
not explicitly passed toreject()
inside the constructorPromise
in a loop using a functionasync
? -
Why only the value is
Promise
returned in.then()
, although the array is returned from the functionasync
, when one of the objectsPromise
iterated over in the loop function isreject()
called inside thePromise
constructorresolver
function?
source to share
When trying to code, for example, where used Promise
and expected to log an error in .catch()
, explicitly pass Error()
, preferably with the appropriate message as a parameter, in reject()
from the Promise
constructor or Promise.reject()
; and replace it with the help of console.error()
on console.log()
on .catch()
to distinguish between error, which you would expect to be written as Error()
, but are not allowed value Promise
, where the allowed value and the deviation may prove the same.
source to share