1

I'm worried about this code:

knex('person').where('id','=', 1).then(result => {
    const person = result[0]; // the code I worry - result should contain only ONE element
});

If I was using C#, I would use Linq's Single, it would fail fast and throw an exception if there are more than one element in result, say the where clause is forgotten or has wrong condition.

How would I implement that in JavaScript?

The SE I loved is dead
  • 1,517
  • 4
  • 23
  • 27
Hao
  • 8,047
  • 18
  • 63
  • 92
  • Why not just [`limit`](http://knexjs.org/#Builder-limit) it? – Mike Cluck Oct 25 '16 at 21:10
  • 1
    Just `return Promise.reject("More than 1 result")` if the condition is met. – 4castle Oct 25 '16 at 21:16
  • @MikeC the code would not fail if it returns more than row due to for example, a wrong where logic. if LIMIT is used, the code will silently continue even when it's receiving random data due to wrong where logic – Hao Oct 26 '16 at 17:10
  • @Hao Sure, but you could limit the results to, say, 2 so that it does not get any more data than necessary. Check `result.length > 1` and throw an error. – Mike Cluck Oct 26 '16 at 19:02
  • @MikeC Yes could use LIMIT 2 and result.length check, I'm looking for a one-liner though. `result.Single()` would cause an exception in C# if Single detected more than one element – Hao Oct 26 '16 at 22:15
  • If possible add OrderBy to your query and always select the first one.(if applicable) – Shriram Manoharan Oct 27 '16 at 06:28
  • @ShriramManoharan that would still cause silent errors to slip through, say the where has wrong condition. would want to make things fail fast if there is wrong implemented code – Hao Oct 27 '16 at 09:34
  • @Hao There's nothing built-in to the system to give you a one-liner + error. You could write your own function which extends that library and make it throw an error though. – Mike Cluck Oct 27 '16 at 13:07

0 Answers0