-1

So, I have two ajax calls, which are chained in a promise.

For example

promiseData.then(res1, res2) {
 let responseOneParsed = JSON.parse(res1)
 let responseTwoParsed = JSON.parse(res2)
}

I am concatenating these two, like this

concatenatedArr = responseOneParsed.data.concat(responseTwoParse.data)

So, this is clear. But, sometimes one of these two ajax calls returns undefined, since the response is empty (should be), and I get the error:

  error  TypeError: Cannot read property 'concat' of undefined

Which is again very clear, but how can I scale this code to accept one of these parameters, if other is undefined, so it does not fail? Is .concat() used wrongly here?

stormec
  • 179
  • 1
  • 10
  • How about a very basic check, like `if (responseOneParsed.data) ...` –  Jun 13 '18 at 19:35
  • I understand why this happens @JonathanLonowski, but need to check for that case.. – stormec Jun 13 '18 at 19:36
  • It doesnt give error when the 2nd rsponse is undefined because it is passed as an argument to the function, its no calling the function. Its when we call a function using an undefined value that we get an error as mentioned in the question. – Nandita Sharma Jun 13 '18 at 19:36
  • Just make the API return `[]` when the result is empty so the code always works. –  Jun 13 '18 at 19:37
  • @ChrisG, I can't API is from third-party. If it is undefined, it is not returning array at all, but object. – stormec Jun 13 '18 at 19:39
  • A promise `then` will *never* pass two arguments to the callback, so `res2` is *always* undefined. – Bergi Jun 13 '18 at 19:40
  • It passes Bergi.., since $.when() was used previously – stormec Jun 13 '18 at 19:41

2 Answers2

4

You can easily make it with || operator and empty array: []

like this concatenatedArr = (responseOneParsed.data || []).concat(responseTwoParse.data || [])

BotanMan
  • 1,357
  • 12
  • 25
1

Isn't this just a case of proper sanity checking?

Check to see if responseOneParsed.data is valid, if it is, call concat, else, apply the second data.

 concatenatedArr = responseOneParsed.data ? 
   responseOneParsed.data.concat(responseTwoParse.data ? responseTwoParse.data: [] )
   :responseTwoParse.data
Rich
  • 1,567
  • 14
  • 24