Why doesn't .then() execute at all for my Promise?


AlphaHowl

I have a chain resolveof promises to run, promises will appear when complete (see code below for more context), and want my code .then()block to run...but it doesn't. Here is my code:


function notifications_for_each_in_array(iteration, the_array, error_array) {
    
    return new Promise(function(resolve, reject) {

        if(!iteration) iteration = 0;
        var error_array = error_array || [];

        var user_id = the_array[iteration];

        $.ajax({
            url: ".....my_url.....",
            type: "PUT",
            data: JSON.stringify({test: [user_id]}),
            success: function() {
                // ...
            }

        }).done(function(rez) {
            error_array.push(rez);

            iteration++;

            console.log("will stop: " + (the_array[iteration] == undefined));

            if(the_array[iteration] == undefined) { // reached the end
                console.log("Resolving...");
                resolve(error_array);
            } else {
                if(the_array[iteration] != undefined) {
                    console.log("Next: " + iteration);
                    notifications_for_each_in_array(iteration, the_array, error_array);
                } 
            }
            
            
        }).fail(function(err) {
            console.error(err);
        });
    });
}

The above function works, but when I call it using .then(), the .then()block doesn't run. In this example, I never get the alert (PS: I also tried defining notifications_for_each_in_arrayas a asyncfunction, and using await, but got the same result):

notifications_for_each_in_array(0, [0,1,2,3], [])
.then(function(res) {
    alert("here is then()"); // I never get alerted!
});
Demitz

Your code is unnecessarily complex. Basically, all you need to do is iterate over the input array and use async/await to run them.

Here is a demo that shows how to loop easily. Your call supports async/await $.ajaxas shown in my fake call to httpbin . Also note that I never explicitly create a new Promisefunction, just declare the function as async.

async function notifications_for_each_in_array(arr) {
  const errors = [];
  for(var i=0;i<arr.length;i++) {  
     var result = await makeAjaxCall(arr[i]);
     errors.push("response from:" + result.args.id);
  }
  return errors;
}

const makeAjaxCall = (data) => {
  return $.ajax({
    url:"https://httpbin.org/get?id=" + data,
    method:"GET",
    type:"JSONP"
  })
}

const demo = async () => {
  var result = await notifications_for_each_in_array([0,1,2,3]);
  console.log(result);
}

demo()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

You should also note that you don't actually need to wait for each HTTP call before making the next one. You can run them all in parallel!

async function notifications_for_each_in_array(arr) {
  const errors = await Promise.all(
    arr.map(async data => {    
      const res = await makeAjaxCall(data)
      return "response from: " + res.args.id;    
    })
  );
  
  return errors;
}

const makeAjaxCall = (data) => {
  return $.ajax({
    url:"https://httpbin.org/get?id=" + data,
    method:"GET",
    type:"JSONP"
  })
}

const demo = async () => {
  var result = await notifications_for_each_in_array([0,1,2,3]);
  console.log(result);
}

demo()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Related


Why doesn't .then() execute at all for my Promise?

AlphaHowl I have a chain resolveof promises that I want to run, promises will appear when done (see code below for more context), and want my .then()block of code to run...but it doesn't. Here is my code: function notifications_for_each_in_array(iteration, th

Why doesn't .then() execute at all for my Promise?

AlphaHowl I have a chain resolveof promises to run, promises will appear when complete (see code below for more context), and want my code .then()block to run...but it doesn't. Here is my code: function notifications_for_each_in_array(iteration, the_array, er

Why doesn't .then() execute at all for my Promise?

AlphaHowl I have a chain resolveof promises that I want to run, promises will appear when done (see code below for more context), and want my .then()block of code to run...but it doesn't. Here is my code: function notifications_for_each_in_array(iteration, th

Why doesn't .then() execute at all for my Promise?

AlphaHowl I have a chain resolveof promises to run, promises will appear when complete (see code below for more context), and want my code .then()block to run...but it doesn't. Here is my code: function notifications_for_each_in_array(iteration, the_array, er

Why doesn't .then() execute at all for my Promise?

AlphaHowl I have a chain resolveof promises to run, promises will appear when complete (see code below for more context), and want my code .then()block to run...but it doesn't. Here is my code: function notifications_for_each_in_array(iteration, the_array, er

Why doesn't my promise chain resolve?

VaultBoy14 I'm just using promises. I wrote this method in a vue component. Debugging it, the api definitely returns data and reaches the commented line. When the function returns, it never reaches the original caller .then method. All the alerts I have set ar

Why doesn't my promise do the job?

thanks I'm struggling with promises, I think I understand the concept, but for my project this doesn't work, Here is some of my code: (I'm coding in TypeScirpt using Angular 2 and Ionic2) ngOnInit() { Promise.resolve(this.loadStatut()).then(() => this.testSt

Why doesn't my promise chain resolve?

VaultBoy14 I'm just using promises. I wrote this method in a vue component. Debugging it, the api definitely returns data and reaches the commented line. When the function returns, it never reaches the original caller .then method. All the alerts I have set ar

Why doesn't my promise chain resolve?

VaultBoy14 I'm just using promises. I wrote this method in a vue component. Debugging it, the api definitely returns data and reaches the commented line. When the function returns, it never reaches the original caller .then method. All the alerts I have set ar

Why doesn't my promise chain resolve?

VaultBoy14 I'm just using promises. I wrote this method in a vue component. Debugging it, the api definitely returns data and reaches the commented line. When the function returns, it never reaches the original caller .then method. All the alerts I have set ar

Why doesn't my promise chain resolve?

VaultBoy14 I'm just using promises. I wrote this method in a vue component. Debugging it, the api definitely returns data and reaches the commented line. When the function returns, it never reaches the original caller .then method. All the alerts I have set ar

Why doesn't my promise chain resolve?

VaultBoy14 I'm just using promises. I wrote this method in a vue component. Debugging it, the api definitely returns data and reaches the commented line. When the function returns, it never reaches the original caller .then method. All the alerts I have set ar

Why doesn't my promise chain resolve?

VaultBoy14 I'm just using promises. I wrote this method in a vue component. Debugging it, the api definitely returns data and reaches the commented line. When the function returns, it never reaches the original caller .then method. All the alerts I have set ar

Why doesn't my promise chain resolve?

VaultBoy14 I'm just using promises. I wrote this method in a vue component. Debugging it, the api definitely returns data and reaches the commented line. When the function returns, it never reaches the original caller .then method. All the alerts I have set ar

Why doesn't my promise chain resolve?

VaultBoy14 I'm just using promises. I wrote this method in a vue component. Debugging it, the api definitely returns data and reaches the commented line. When the function returns, it never reaches the original caller .then method. All the alerts I have set ar

Why doesn't my promise chain resolve?

VaultBoy14 I'm just using promises. I wrote this method in a vue component. Debugging it, the api definitely returns data and reaches the commented line. When the function returns, it never reaches the original caller .then method. All the alerts I have set ar

Why doesn't my promise chain resolve?

VaultBoy14 I'm just using promises. I wrote this method in a vue component. Debugging it, the api definitely returns data and reaches the commented line. When the function returns, it never reaches the original caller .then method. All the alerts I have set ar

Why doesn't this timer execute in my Fragment?

Marcus Cantu As the question states, why is this timer not executing? I set it in a fragment and I think it has something to do with my runOnUiThread, but I'm not sure. Also I should add that I don't get any errors or anything that it won't execute. final Weak

Why doesn't my Dockerfile execute the command

Giuliazin I am trying to dockerise my Laravel application. Here is my dockerfile: FROM php:7.1.14-fpm WORKDIR /app COPY . /app COPY ./entrypoint.sh /tmp RUN touch /app/resources/assets/less/_main_full/main.less \ && touch /app/database.sqlite \ && apt-get up

Why doesn't my Dockerfile execute the command

Giuliazin I am trying to dockerise my Laravel application. Here is my dockerfile: FROM php:7.1.14-fpm WORKDIR /app COPY . /app COPY ./entrypoint.sh /tmp RUN touch /app/resources/assets/less/_main_full/main.less \ && touch /app/database.sqlite \ && apt-get up

Then the JavaScript Promise doesn't execute

Adam 91 Holt I'm trying to implement a Promise in the following JavaScript code, but for some reason the process.then function never actually happens. Can anyone see why? I have setup new Promise and it has tested it as per the console log but it never execute

Why doesn't my program remove "all"?

Sankov My problem is that when I output this code, it doesn't output what I want to remove "all". It outputs exactly what the first print statement does. Here is my code: // RemoveAll // Spec: To remove the "all" // ArrayList remove() exercise import java.uti