简体   繁体   中英

Nested promise not throwing error in parent catch block

My code :


return resultSet.reduce (prev,next)=> {
return function1 ({
}).then(response => {
    console.log('suscess' + someID)
    return functionA (response.someID)
}).catch (err => {
    console.log('failed' + someID)
    return functionB (response.someID)
}) 

}, promise.resolve());


function1: function (){
    return function2_Credentials().then{
        return function3_insertSqlRecord().then{
            return function4_appSearch().then (function(response){
                return function5().then (return response)
                    .catch (function (error){
                     throw Error(error);
                    });
             });
        }.catch (function(error){
                throw Error(error);
            });
    }
}.catch (function(error){
                throw Error(error);
            });

Inside my nested promise, if any of the inner functions failed I can get the error in catch block but it is not available function1 catch block. For example If i get function4_appSearch fails and return any error that error is accessible to the last catch block but not carried away until the function1's catch block. why am I not getting the error at console.log('failed' + someID) ? and how do I get access of error from child promise untill to the parent pormise's catch block?

Your current code isn't valid; it has multiple syntax errors, and everything ever passed to a .then needs to be a Promise. Instead of

return function3_insertSqlRecord().then{
  return function4_appSearch().then

you should do something like

return function3_insertSqlRecord()
  .then(function4_appSearch)
  .then( // etc

This keeps your code flat and ensures that that the Promises each function generates are chained properly.

If you want the caller of function1 to handle the error, then just let the error propagate up the Promise chain - don't .catch inside function1 , because whenever you .catch , a resolved Promise results (but you want the caller to be able to see a rejected Promise). You can explicitly throw inside the .catch to make the Promise reject, but if that's all you're doing inside the .catch , there isn't really any point.

Try this instead:

function function1() {
  return function2_Credentials()
    .then(function3_insertSqlRecord)
    .then(function4_appSearch)
    .then(function5);
}

There also isn't any point to using reduce if you aren't going to use the accumulator (here, prev ) or the item in the array you're iterating over ( next ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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