0

I have the following db calls

const x = await doThis();
cons y = await doThat(x);

return somethingElse(x,y)

This works fine but when a promise isn't returned correctly, debugging is impossible. I want to write code something like the following

  try {
    const x = await doThis();
  } catch (e) {
    console.log(e);
  }
  try {
    cons y = await doThat(x);
  } catch (e) {
    console.log(e);
  }
  return somethingElse(x,y);

However, I get the following error:

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReferenceError: x is not defined

Do the try/catch blocks stop the code from running asynchronously? How do I fix this?

2 Answers 2

6

When you declare variables with let or const they are bracket-scoped.

In you code part x and y are bracket-scoped to their try statements - so why they are not defined outside of try. You need to define them before try statements.

You can also replace const with var. This will hoist the variables declaration in the start of the function (based on the return statement that it is a function) and will work - x and y will be visible to whole function, but I recommend to use the approach with let declaration.

let x, y;

try {
   x = await doThis();
} catch (e) {
   console.log(e);
}

try {
   y = await doThat(x);
} catch (e) {
   console.log(e);
}

return somethingElse(x,y);
Sign up to request clarification or add additional context in comments.

2 Comments

Ah, got it - I'll mark as correct when it let's me.
Or if you're lazy, could use var instead of const to hoist them to function scope. Good catch though, I didn't spot that at first.
0

It has to do with scoping. You declare x and y inside a try block so they are only scoped inside that block. Declare them outside the block and assign the values inside the try blocks. Keep in mind that the values could still be undefined if there is an exception in which case you should check for a value before proceeding to the next call.

let x, y;

try {
  x = await doThis();
} catch (e) {
  console.log(e);
}

try {
  if(x) // check if x has a value, if there was an exception then x could be undefined
     y = await doThat(x);
} catch (e) {
  console.log(e);
}

if(y) // check if y has a value, if there was an exception then y could be undefined
    return somethingElse(x,y);
return null;// or something else??

1 Comment

If you're using var, you technically don't need to move the declarations out of the try/catch blocks since var is a function scope declaration.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.