Get data from first .then based on condition on second .then

Viewed 123

I used promises as advised in my previous question to get values from 2 async calls.

But I want the results from my first call based on a condition of my second call. I keep getting undefined when I do what I am doing. How do I get my desired result.

First JSON:

let first_json = [
    {
        "company": "one"
    },
    {
        "company": "two"
    },
    {
        "company": "three"
    }
]

The second JSON is dependent on the first one and is of similar format.

Using promises I did:

$.getJSON(first_json)
 .then(first_data =>
      first_data.map(d => {
          return d.company;
      })
  )
 .then(promises => Promise.all(promises))
 .then(company => company.map(c => {
        let second_json = json_string + c;
        $.getJSON(second_json, function(data) {
            if (data.length > 0) return c;
        });
    }))
 .then(arr => {
     console.log(arr);
  });

arr for me is supposed to return ['one', 'three'] but is instead returning: [undefined, undefined, undefined].

Why is that happening and how do I fix it?

2 Answers

Your callback is asynchronous, so, unless you 'await' it with a then, it won't be available to you right away, and therefore you can't act based on it.

Instead, do it like this:

$.getJSON(first_json)
  .then(first_data =>
    first_data.map(d => {
      return d.company;
    })
  )
  .then(promises => Promise.all(promises))
  .then(company => company.map(c => {
    let second_json = json_string + c;
    return $.getJSON(second_json)
      .then(data => {
        if (data.length > 0) return c;
      });
  }))
  .then(promises => Promise.all(promises))
  .then(arr => {
    console.log(arr);
  });

You're applying the Promise.all in the wrong stage:

$.getJSON(first_json).then(first_data => {
    const companies = first_data.map(d => {
        return d.company;
    });
    const promises = companies.map(c => {
//        ^^^^^^^^
        let second_json = json_string + c;
        return $.getJSON(second_json).then(data => {
//      ^^^^^^
            if (data.length > 0) return c;
        });
    });
    return Promise.all(promises);
//         ^^^^^^^^^^^
}).then(arr => {
    console.log(arr);
});
Related