Search code examples
javascriptes6-promise

I execute Promsie.all () in Promise's then () method, and the method in Promsie.all () is executed first. The code is as follows


 <script type="text/javascript">
    const url="http://127.0.0.1/index.php?id=";
   let task = [];
   let task01 = function()
   {
        return new Promise( function(resolve , reject){
            $.ajax({
              url: url+1,
              context: document.body,
              success: function(){
                resolve('success');
                 console.log("01");
                }
           });
        })
   }
      task[0]= function(){
        new Promise( function(resolve , reject){
            $.ajax({
              url: url+2,
              context: document.body,
              success: function(){
                resolve('success');
                 console.log("02");
                }
           });
        })
      }


     task[1] = function(){
       new Promise( function(resolve , reject){
           $.ajax({
             url: url+3,
             context: document.body,
             success: function(){
               resolve('success');
                console.log("03");
               }
          });
       })
     }


    task01().then(function(value){
         Promise.all(task);
    })


</script>

I execute Promsie.all () in Promise's then () method, and the method in Promsie.all () is executed first. The code is as follows Where did I go wrong ,my code result as follow the pictrue enter image description here


Solution

  • From the look of your code, I do not think that the code in your task array functions is executed at all. Promise.all expects array /iterable object to be exact/ of promises but you are passing it just an array of functions, which are never going to be executed. In order, this example to work first your functions in your task array have to return promise, and second, you have to envoke those function. Something similar to:

    task[0] = function() {
      return new Promise( function(resolve, reject) {
        $.ajax({
        url: url + 2,
        context: document.body,
        success: function(){
          console.log('02');
          resolve('success');
        }
      });
    });
    

    };

    task[1] = function() {
      return new Promise(function(resolve, reject){
        $.ajax({
          url: url + 3,
          context: document.body,
          success: function(){
            console.log('03');
            resolve('success');
          }
        });
      });
    };
    
    task01().then(function(value) {
      const taskPromises = task.map((fn)=>fn());
      Promise.all(taskPromises);
    });
    

    As a side note your code is a bit messy, please try to write more clear code;