问题
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