1

I have a code structure like this:

function f1() {
  return f2().then(function(res2) {
    var arr = res2;
    var a = "default";
    arr.forEach(function(element) {

      if (element.condition) {
        ...
      } 
      else {
        f3().then(function(res3) {
          a = res3;
          });
      }
    };
    return [arr, a];
  });
};

f1().then(function(result) {
  console.log(result[0]);
  console.log(result[1]);
  });

result[0] (array) has actual value of array, however, result[1] (a) is "default". How should I modify the code above to get the actual value of 'a'?

Chris Gabler
  • 179
  • 1
  • 1
  • 14
  • can you show the `f2` method please? – Joey Gough Oct 17 '18 at 12:37
  • Looks like `element.condition` is never falsey? –  Oct 17 '18 at 12:37
  • If `a` is set asynchronously from a second call (which seems like it does), you can't do it in this fashion. You'll need to use `Promise.all` to wait on the result of all of the async operations done on `arr`. – Madara's Ghost Oct 17 '18 at 12:39
  • @JoeyGough I edited the code to make it clearer. f2 function returns the response of the first fetch request, f3 function returns the response of the second fetch request – Chris Gabler Oct 17 '18 at 12:45
  • @ChrisG no, it does get false at some moment. If I print value of 'a' in each iteration, the result looks like 'default', 'default', 'default', 'default', 'actual_value', 'actual_value'... still it returns 'default' – Chris Gabler Oct 17 '18 at 12:47
  • @ChrisGabler The basic idea is to use `Promise.all()` instead of `arr.forEach`, since you have asynchronous operations in there. –  Oct 17 '18 at 12:53

0 Answers0