0

My function caller calls a function parent which itself calls child. If child errors then I need to be returned to caller.

When I reject the promise this works, however when I try and return the promise resolve it's not returned to caller

function caller() {
  return parent()
}       

async function parent(){
  const child = await foo(
    // more code
  ).catch(error=>{
    if(error === 123) {
      return Promise.resolve("This was resolved"); 
    }
    return Promise.reject("This was rejected");
  })
}

I think a try / catch block would work but I prefer the syntax above.

Evanss
  • 23,390
  • 94
  • 282
  • 505
  • 1
    You are mixing the async/await syntax and the `.then().catch()` syntax. You can use one or the other, not both. If you are using async/await, you need a try-catch to catch the promise rejection. Also I don't think your code would work since your function is not async (`function parent()` should be `async function parent()` if you want to use `await` in the function block) – Seblor Jul 03 '19 at 10:25
  • because your `parent()` function does not return anything, especially not `const child`. But Errors bubble up the call stack. – Thomas Jul 03 '19 at 10:29
  • What about using `try..catch` instead with `await`? https://stackoverflow.com/a/44664037/2275797 It would be way easier to read, even for those who are not used to javascript. – briosheje Jul 03 '19 at 10:38

1 Answers1

0

The problem is you are not returning the child from parent.

Here is a simple example,

function caller() {
    return parent()
}

 async function parent() {
    const child = await foo()
    .catch(error => {
        if (error === 123) {
            return Promise.resolve("This was resolved");
        }
        return Promise.reject("This was rejected");
    })
    return child;
}

function foo(){
    return Promise.reject(123);
}
caller().then(console.log);//This was resolved

Note: then again mixing async/await with then/catch is not recommended at all. But I think the obvious reason is, readability.

Aritra Chakraborty
  • 12,123
  • 3
  • 26
  • 35