给定
(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));
错误()记录在.catch()
如果我们扩展模式以使用循环,则错误记录在.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));
如果我们使用循环调用一个以上的函数来返回Promise且未将Error()显式传递给Promise构造函数解析器函数的reject(),则catch()不会捕获该错误,并且不会返回数组res,仅传递给resolve()的Promise值位于
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));
问题:
>为什么在异步函数的循环内,当Promise构造函数中没有将Error()显式传递给reject()时,拒绝()调用不会传播到.catch()?
>当在Promise构造函数解析器函数中调用在循环reject()函数中迭代的Promise对象之一时,为什么从异步函数返回一个数组,为什么只有一个Promise值返回给.then()?
解决方法:
If we […] do not explicitly pass
Error()
toreject()
of Promise constructor resolver function.catch()
does not catch the error
可以,因为那时没有错误.但是catch会捕获您传递给拒绝的任何内容,即值1,它的正确记录是正确的.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。