Using return as one of multiple statements in ternary expression [duplicate]

强颜欢笑 提交于 2019-12-25 07:58:33

问题


I have this code:

  err ? (reject(err), return)
      : resolve(db)

Which returns:

SyntaxError: Unexpected token return

However this works:

err ? (reject(err), console.log('test'))
    : resolve(db)

Why is that return can't be used in this situation? Is there other alternative to stop function execution while using ternary operator for multiple statements?


回答1:


It's a ternary expression, the expression as a whole must evaluate to a value, and thus contain only expressions.

You can't say a = 1 + return; either.

Is there other alternative to stop function execution while using ternary operator for multiple statements?

The if statement...

if (err) { reject(err); return }

resolve(db);



回答2:


err ? (reject(err), return)
    : resolve(db)

Is there other alternative to stop function execution while using ternary operator for multiple statements?

Ternary operators are not like if else in the sense of including an implicit return statement. So in order to return asap once the condition satisfies, you might properly do as follows.

return err ? reject(err)
           : resolve(db);


来源:https://stackoverflow.com/questions/39895655/using-return-as-one-of-multiple-statements-in-ternary-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!