1

this is my code, which works not perfectly yet:

function func1() {
       $('.lastStateText').html("<img src='images/Loading.gif' />").fadeIn('slow')
       $('.lastStateText').each(function() {
          lastState('xxx').then(result => 
             $( this ).fadeOut(500, function(){
                $( this ).text(result)
                alert(result)
             })
          )
       })
    }

    function lastState(parameter) { 
       return new Promise( done =>
          $.getJSON("myFile.php", {
             parameter: parameter
          }, function(result) {
                done(result); 
             }
          )
       )
    }

What happens here?

  1. I call func1
  2. This function will show a Loading.gif in each element with the class "lastStateText" with a fadIn effect
  3. A loop will go through all lastStateText elements, fadeOut it out and call each time the next function lastState with a parameter 'xxx'. 4 The lastState function will get the result of myFile.php and give it back to the func1.
  4. Now the func1 should set the result into the lastStateText element <- but this doesn't work. now result will shown in the element. I checked with alert(result) if the result will be available and yes -> the result is there. but not visible in my lastStateText element.

Where is my fault?

Trombone0904
  • 4,132
  • 8
  • 51
  • 104
  • I think that there is an issue with executing a promise in a forEach loop. Try something like in https://stackoverflow.com/a/38362312/1985912. – Striped Feb 02 '18 at 10:38
  • 2
    I see two potential problems: You fade-out the element and put the content in when that is done, so you will not see it, 2. `this` is not what you think it is and you should set it to a variable in your `each` function. – jeroen Feb 02 '18 at 10:38

1 Answers1

0

I am assuming you have to support old(ish) browsers since you do not use arrow functions or native promises and do not use transpilers.

The traditional way of parallel promises could be using the jQuery.when method, that will make all the requests for you.

It would look something like this:

function func1() {
  $.when.apply(//jQuery version of Promise.all
    $,
    $('.lastStateText')
    .html("<img src='images/Loading.gif' />")
    .fadeIn('slow')
    .map(
      function(index,element){
        return lastState('xxx').then(function(result) {
          $element = $(element);
          $element.fadeOut(500, function(){
            $element.text(result);
            $element.fadeIn(500);
            console.log("result",result);//changed to console.log
          })
        })
      }
    )
  ).then(
    function(){console.log("finished");}
  ).catch(
    function(){console.warn("something went wrong:",err);}
  );
}
function lastState(parameter) { 
    return $.getJSON(//getJSON already returns a promise like
      "myFile.php", 
      {
          parameter: parameter
      }
    );
}
HMR
  • 37,593
  • 24
  • 91
  • 160