抓住承诺与承诺的差异
new Promise(function(resolve, reject) {
setTimeout(() => {
throw new Error("Whoops!");
}, 1000);
}).catch(alert);
来自 https://javascript.info/promise-error-romise-error处理 代码块将行不通,因为此处的错误不是在执行人运行时生成的错误,而是在以后。
Promise.all([
new Promise((resolve, reject) => setTimeout(() => resolve(1), 1000)),
new Promise((resolve, reject) => setTimeout(() => reject(new Error("Whoops!")), 2000)),
new Promise((resolve, reject) => setTimeout(() => resolve(3), 3000))
]).catch(alert); // Error: Whoops!
为什么捕获量在2秒钟后捕获错误? 这看起来与第一个代码块相矛盾,说catch无法正常工作
。
通常,我如何调查所有Promise.los.的承诺?我想索引“承诺的数组”以获取其中1个状态,但不能执行此语法result_promise_all [0]
。
最好的话,如果答案可以解释执行顺序,哪种代码何时会触发在Microtask和Macrotask队列上以及何时脱离队列的情况。
From https://javascript.info/promise-error-handling
new Promise(function(resolve, reject) {
setTimeout(() => {
throw new Error("Whoops!");
}, 1000);
}).catch(alert);
It says the catch in this code block will not work because here the error is generated not while the executor is running, but later. So the promise can’t handle it.
However at https://javascript.info/promise-api
Promise.all([
new Promise((resolve, reject) => setTimeout(() => resolve(1), 1000)),
new Promise((resolve, reject) => setTimeout(() => reject(new Error("Whoops!")), 2000)),
new Promise((resolve, reject) => setTimeout(() => resolve(3), 3000))
]).catch(alert); // Error: Whoops!
Why does the catch work to catch the Error after 2 seconds?
This looks like it contradicts the 1st code block saying catch won't work
What is different about Promise.all?
Generally how do I investigate the returned promise from Promise.all? I want to index into that "array of promises" to get the state of 1 of them but can't do this syntax result_promise_all[0]
.
Best if the answer can explain execution order, when which code triggers what to go on microtask and macrotask queues, and when they get off the queue.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
第一个示例和第二个示例之间的区别只是您在第一个示例中没有拒绝,而在
Promise.all
中拒绝:The difference between the first and second example is just that you are not rejecting in the first one, while you are rejecting in the
Promise.all
: