0

from what I've read, using try/catch is the "right" way to handle errors when using async/await. However, I ran into an issue in trying to use the response of a request if I put it in a try/catch block:

    try {
        async someMethod () {
            const result = await someRequest()
        }
    } catch (error) {
        console.log(error)
    }

    console.log(result) // cannot access `result` because it is not defined... 

Therefore, is there a better way to handle errors AND be able to access request responses from async/await calls? The only other way I can think of is to put the ENTIRE code block inside of the try/catch block.. but I feel like there is a more elegant way..

Thanks in advance!

John Grayson
  • 1,378
  • 3
  • 17
  • 30
  • 1
    The `try..catch` should be around the `await` statement, not around the function definition. – Felix Kling Jun 01 '18 at 23:44
  • What you posted is an `Uncaught SyntaxError: Unexpected identifier`. Please post valid syntax, otherwise we can't help you. – Bergi Jun 02 '18 at 09:23
  • possible duplicate of [Correct Try…Catch Syntax Using Async/Await](https://stackoverflow.com/q/44663864/1048572) – Bergi Jun 02 '18 at 09:25

2 Answers2

-1
(async () => {
  result = null;
  async someMethod(){
    result = await someRequest();
  }
  console.log(result)
})()
.catch(error => console.log(error));
Felix Fong
  • 969
  • 1
  • 8
  • 21
-1

Either you should declare variable outside of the block scope or just don't use any keyword in front of result. This way it will make it a global variable and you can access it outside the block code. You can write it like this: -

try {
    async someMethod () {
        result = await someRequest()
    }
} catch (error) {
    console.log(error)
}

console.log(result)

Or you can also use a shorter method instead of try catch to make code cleaner and you can also know from where the error is coming.

async someMethod () {
        result = await someRequest().catch(err=>{
            console.log(err)
        })
}
console.log(result)
Rajat
  • 71
  • 5