Sparsh Pipley
Sparsh Pipley

Reputation: 451

Execute function in order in javascript?

I'm having this piece of code written in javascript

preDefineListName = ['Applied', 'Test taken', 'SWS Interview', 'Candidate', 'Rejected'];

for (var i = 0; i < preDefineListName.length; i++) {
      Trello.addList(data.id, preDefineListName[i]);
};

Trello.addList = function (trelloBoardId, listName) {
    return $http.post('https://api.trello.com/1/lists', {
        idBoard: trelloBoardId,
        name: listName,
        key: trelloKey,
        token: trelloToken
    });
};

now above function Trello.addList in the for loop makes a list on the trello.com with the given names in preDefineListName. The problem is the lists are not appearing in the order as they passed.

What should I do to make it in proper order. and i've to call function in the loop so I can't change it.

Upvotes: 0

Views: 178

Answers (2)

Dominik Schreiber
Dominik Schreiber

Reputation: 2771

Your Trello.addList returns a Promise and is asynchronous (as it executes an http call). You therefore need an asynchronous loop instead of the for loop as well. This would be a .forEach call on the preDefineListName list.

You can however use .map as well, which lets you return the result of the Trello.addList calls and then use $q.all to wait until all addList calls are done:

$q.all(preDefineListName.map(function(name) {
    return Trello.addList(data.id, name);
})).then(function success(results) {
    // do something with the results
}, function error(reasons) {
    // handle errors here
});

Upvotes: 1

unxp
unxp

Reputation: 358

Use promises and recursion. Looks a bit hacky, but will make things synchronous:

preDefineListName = ['Applied', 'Test taken', 'SWS Interview', 'Candidate', 'Rejected'];

Trello.addList(data.id, preDefinedListName); // Initiate list adding

Trello.addList = function(trelloBoardId, listNames) {
   if(!listNames.length) {
      return;
   }

   var listName = listNames[0];
   listNames.splice(0, 1); // Remove first element from array

   $http.post('https://api.trello.com/1/lists', {
        idBoard: trelloBoardId,
        name: listName,
        key: trelloKey,
        token: trelloToken
   }).then(function(response) {
       Trello.addList(trelloBoardId, listNames); // Call the function again after this request has finished.
   });
}

Upvotes: 0

Related Questions