Thian Kian Phin Thian Kian Phin - 25 days ago 10
Ajax Question

jquery $(data).each doesn't work with promises?

I have an

each()
loop in my AJAX handler to do push into my
temp
array, but in the end I still get an empty array. It's strange, I remember I once use promise on
each()
so it has no problem.

var temp = [];
$.ajax({
type: 'GET',
url: '/endpoint',
success: function(data) {
$(data).each(function() {
//do some stuff
console.log(something); // working
temp.push(something);
}).promise().done(function() {
console.log(temp); // still empty array?!
});
});


update: here's how people has done it http://stackoverflow.com/a/8941358/7095330

Answer

Reducing your script to what your question is asking, everything seems to be working fine. Hopefully this will help you find out that your problem is somewhere else in your code:

var temp = [];
var data = [1,2,3,4,5,6,7,8];

$(data)
    .each(function(thing) {
      //do some stuff
      console.log(thing); // working
      temp.push(thing);
    })
    .promise()
    .done(function() {
      console.log(temp); // still empty array?!
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

However the promise().done() is pretty weird; I can't see why you'd need that there.

Sounds like a case for map, where you have an input array and you want to transform its contents.

var data = [1,2,3,4,5,6,7,8]

var changedData = data.map(function (datum) {
  // do stuff
  return 'did stuff to ' + datum;
});

console.log(changedData)

Unless what you were trying to do was the following, which still works. PEBKAC error perhaps?

var temp = [];
$.ajax({
    type: 'GET',
    url: 'https://google.com/',
    // replaced success: with error:, for example's sake
    error: function(data) {
        $(data).each(function() {
            //do some stuff
            console.log('something');
            temp.push('something');
        }).promise().done(function () {
            console.log('each done', temp);
        });
    },
    done: function() {
        console.log('ajax done:', temp);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments