简体   繁体   English

返回子承诺拒绝时,不会触发最高承诺.catch

[英]Top promise .catch not triggered when returned child promise rejects

I have this: 我有这个:

function sayHello() {
    return new Promise( resolve => {
       throw new Error('reject');
    });
}

new Promise(resolve => sayHello()).then(ok => console.log('ok:', ok)).catch( err => console.error('err:', err) );

However the .catch never triggers. 但是.catch永远不会触发。 I though if I return a promise within a promise, it gets chained so that top level .then and .catch are re-reouted to child .then and .catch ? 不过,我觉得,如果我一个承诺内返回一个承诺,它就会被链接,使顶层.then.catch重新reouted儿童.then.catch

The problem is with your "new error" thrown at the Promise callback. 问题在于你在Promise回调中抛出的“新错误”。 Throwing an error inside promise executor does not automatically reject it. 在promise执行程序中抛出错误不会自动拒绝它。
Edit: actually Promise executor does automatically reject the promise when an exception is thrown. 编辑:实际上,Promise执行程序在抛出异常时自动拒绝承诺。 Nevertheless, this is not the main cause of your problem. 然而,这不是问题的主要原因。 Also a note - throwing will only work on the "main" level of executor, so any asynchronous job throwing an exception won't automatically reject the promise. 另外一个注意 - 抛出只能在执行者的“主”级别上工作,因此抛出异常的任何异步作业都不会自动拒绝承诺。

Another problem spotted - your Promise chain ( new Promise(resolve => sayHello())... ) is also invalid - you are simply returning a function call result. 发现的另一个问题 - 您的Promise链( new Promise(resolve => sayHello())... )也无效 - 您只是返回一个函数调用结果。 You always have to manually resolve or reject a Promise that you've created with it's standard constructor (aka. new Promise(executorCallback) ). 总是必须手动解析或拒绝使用它的标准构造函数创建的Promise(也就是new Promise(executorCallback) )。

To fix the other problem, you can use "automatically resolved promise", which I think will do what you are trying to achieve: 要解决另一个问题,您可以使用“自动解决的承诺”,我认为这将实现您要实现的目标:

Promise.resolve(sayHello()).then(...)

So in the end, your code should look like this (using the gist you have posted in the comment below by answer): 所以最后,你的代码应该是这样的(使用你在下面的评论中通过回答发布的要点 ):

function sayHello() {
    return new Promise( (resolve,reject) => {
       reject('rawr')
    });
}

Promise.resolve(sayHello()).then(ok => console.log('ok:', ok)).catch( err => console.error('err:', err) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM