-3

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 https://stackoverflow.com/a/8941358/7095330

Community
  • 1
  • 1
Thian Kian Phin
  • 921
  • 3
  • 13
  • 25
  • 1
    There's nothing in the [documentation](http://api.jquery.com/jquery.each/) to suggest that `.each` returns a promise – Liam Nov 07 '16 at 14:14
  • Maybe it's not a dupe, the OP seems to do strange things with a synchronous loop ? – adeneo Nov 07 '16 at 14:15
  • What's confusing me is the braces don't match. There are too many closing `}` – Liam Nov 07 '16 at 14:16
  • 1
    Now that the code is formatted clearly I can see you're missing a `)` to close the `each()`, and the `promise()` call is in the wrong place; it should be on the `$.ajax`, not the `success` handler function – Rory McCrossan Nov 07 '16 at 14:17
  • The code has been changed too much between the really used one and the one pasted here. It doesn't make sense anymore. Maybe the promise is taken on the call to $.ajax in the real code. – Denys Séguret Nov 07 '16 at 14:17
  • 1
    @Liam http://stackoverflow.com/a/8941358/7095330 – Thian Kian Phin Nov 07 '16 at 14:26
  • But `each` is synchonous, why would you even need a promise? – Liam Nov 07 '16 at 14:36
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Liam Nov 07 '16 at 14:37
  • @Liam because in my each I have image.onload – Thian Kian Phin Nov 07 '16 at 15:37
  • 1
    Next time (or this time) please don't forget to include _crucial_ bits of information about what you code does (`image.onload`), and ideally create a snippet, even if broken. – tmslnz Nov 07 '16 at 15:40

2 Answers2

2

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>
tmslnz
  • 1,801
  • 2
  • 15
  • 24
  • I don't believe there is anything asynchronous about whatever he's doing inside the `success` callback. Wrapping `.each` into a Promise in that context makes no difference than using a purely synchronous alternative. Unless I'm thick right now and am missing something obvious… in which case I'd be happy to know. – tmslnz Nov 07 '16 at 14:49
  • The ops performed before he tries to log `temp` are synchronous as it all happens within the `success` callback. – tmslnz Nov 07 '16 at 14:54
1

You forgot a bracket }

var temp = [];
$.ajax({
    type: 'GET',
    url: '',
    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?!
    });
}});

see https://jsfiddle.net/gw10un58/

Nvan
  • 1,126
  • 16
  • 23