0

So I know my problem lies within async, but first I don't really understand why. I tried some code examples online still undefined.

What I understand is that once ajax retrieves the data, then the functions in done are being executed. However, googling has been telling me that the functions are being executed before the data has being retrieved, resulting in the function not passing variable thus resulting in undefined.

jQuery.ajax({
  "url": 'https://d.apicloud.com/mcm/api/card?filter={"where":{},"order":"hot;DESC","skip":0,"limit":20}',
  "cache": false,
  "headers": {
    "X-APICloud-AppId": "A694530933",
    "X-APICloud-AppKey": appKey
  },
  "type": "GET"
}).done(function(data, status, header) {
  //success body
  for (var i = 0; i < data.length; i++) {
    var listliked= "htmlcode"+data[i].id;
    var list20 = "htmlcode"+data[i].user;
    db.selectSql({
      name: 'dm',
      sql: 'SELECT 1 FROM fav WHERE fav.id ="' + data[i].id + '";',
    }, function(ret, err) {
      if (ret.status) {
        if (ret.data[0] != null) {
          $api.append(outputall, listliked);
        } else {
          $api.append(outputall, list20);
        }
      } else {
        alert(JSON.stringify(err));
      }
    });
  }
}).fail(function(header, status, errorThrown) {
  //fail body
})
  • Where you get `undefined` in the given code? The function passed to `done` is called when `ajax` successfully received a response. – t.niese Apr 17 '17 at 09:44
  • What data do you ship by ajax? – Jose Marques Apr 17 '17 at 09:48
  • What data do You receive by ajax? – Jose Marques Apr 17 '17 at 10:10
  • I get undefined from checklike(data[i].id) in the for loop with alert. I think that the data[i].id is not being passed. – user1919987 Apr 17 '17 at 10:17
  • data receive by ajax is json – user1919987 Apr 17 '17 at 10:17
  • If you get `undefined` at `checklike(data[i].id)` , and not a `Can't read property 'length' of undefined` for `for (var i = 0; i < data.length; i++) {` then the `data` holds an array, but it does not contain what you expect. So check the actual content of `data` (add e.g. a `console.dir(data)` in front of the for loop) – t.niese Apr 17 '17 at 10:22
  • sorry guys, I actually left out a piece of code when i tried to make the code simpler to read. Could you have a look at the code agian ? – user1919987 Apr 17 '17 at 10:27
  • This does not change anything, if you don't get the a `Can't read property 'length' of undefined` error for `for (var i = 0; i < data.length; i++) {` then the returned data looks probably different to what you expect. So check the actual content of `data`. – t.niese Apr 17 '17 at 10:32
  • the content of data can be accessed, it's just that when I try to access the data[i].id in db.selectSQL , if I just tried to pass data[i].id to a function and return it back , it becomes undefined – user1919987 Apr 17 '17 at 10:38
  • Where in the code that you show does this happen `[...]if I just tried to pass data[i].id to a function and return it back , it becomes undefined[...]` . Where do you get an `undefined`? If you cannot tell where/which value is `undefined` (the exact location where this happens) then it is not possible to answer. Beside that the `listliked` and `list20` within the callback of your `selectSql` are most likely (assuming that `selectSql` is async) the values of the last element in the array. – t.niese Apr 17 '17 at 10:44
  • I tried changing $api.append(outputall, listliked); to alert(test(data[i].id)) , and test(id) did was return id. the alert turns out undefined. I think the problem is related to selectsql async , but I can't grasp the concept of why that would interact with the for loop. I understand every loop of the for loop as a individual. – user1919987 Apr 17 '17 at 10:53
  • The callback of `selectSql` will be called when the loop is finished. So at the time you call `alert(test(data[i].id))` the `i` will be `data.length`, so `i` points to an index that is larger then the available elements, and as of that `data[i]` is `undefined`. See this [Asynchronous Process inside a javascript for loop](http://stackoverflow.com/questions/11488014), [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486) or [Calling an asynchronous function within a for loop in JavaScript](http://stackoverflow.com/questions/13343340) – t.niese Apr 17 '17 at 10:59
  • Thank you so much, the page you provide was really helpful, i understand now that there are no i when the selectsql actually runs thus returning undefined !! Thanks again for saving me from another day of hair pulling ! – user1919987 Apr 17 '17 at 11:08

0 Answers0