0

I try to understand behavior of try catch'ing async/ await function. Taking an example and invoking function:

(async () => {
    try {
        const res = await new Promise(res => {setTimeout(() => res({a: 1}), 2000)});    
    } catch(err) {
        console.log('err: ', err);
    }
    console.log(res['a']);
})();

It results in error:

Uncaught (in promise) ReferenceError: res is not defined
at <anonymous>:7:14

How the code should be written if I do await assignment in a try block and I want make a further line use of the promise value?

krzyhub
  • 6,285
  • 11
  • 42
  • 68
  • 1
    If the `catch` block is entered, the assignment has failed - further use of the value, if it may not exist, should probably be in the `try` block (call a function with the value as a parameter?) – CertainPerformance Feb 14 '19 at 09:07
  • Okay, but when the `try` block assigne the value after two second, where should be the `console.log(res['a'])`? And, for example, if the succesfully returned value from first `await` assignment would be then used within another `await` assignment should it be placed withing another `try-catch` block inside the first `try-catch` block? – krzyhub Feb 14 '19 at 09:13
  • 1
    See the duplicate. `const` is scoped to the `try` *block*. – deceze Feb 14 '19 at 09:15
  • 1
    Just put it all in the `try`: `const res = await...; const somethingElse = await ` – CertainPerformance Feb 14 '19 at 09:15
  • Okay. I think I understand it now. Thank you. – krzyhub Feb 14 '19 at 09:29

0 Answers0