disruptiveglow
disruptiveglow

Reputation: 95

Creating cards on Trello in a particular order

I'm using the Trello client.js library to create some cards on a Trello list, by looping over rows in a table. However, it's important the cards be created in order. Right now, my code looks like this:

$("#list > tbody > tr").each(function() {
  $item = "Item: "+$(this).children('td').append(' ').text();
  Trello.post("cards", { name: $item,  idList: "myID"});
});

This is working fine to create all the cards; however, they are not always created in the right order. This is not surprising, because the Trello.post function is asynchronous, so the calls are generated in order, but may finish in different amounts of time.

Any ideas how to fix? It seems like I need to block until each call finishes, but I'm not quite sure how to do this. Is there any general or jquery way to do? I can specify a success function for each call, so seems like I might also be able to sort of recurse my way down, but not quite sure how to do this, especially while using the each function.

Upvotes: 0

Views: 288

Answers (1)

Aaron Dufour
Aaron Dufour

Reputation: 17535

You have two options that I can see. You can either do the calls in series or use the pos option to set the order.

Call in series: I would recommend using a library like async, which makes this straightforward:

async.eachSeries($("#list > tbody > tr"), function(item, cb) {
  var title = "Item: "+$(item).children('td').append(' ').text();
  Trello.post("cards", { name: $item,  idList: "myID"}, cb);
}, function() {
  // Done!  Do anything that needs to happen last here.
});

pos: Cards are sorted by their pos value; it defaults to the current last card's pos + 1024, but you can set it to ensure the right order:

var pos = 1024;
$("#list > tbody > tr").each(function() {
  $item = "Item: "+$(this).children('td').append(' ').text();
  Trello.post("cards", { name: $item,  idList: "myID", pos: pos});
  pos += 1024;
});

Upvotes: 2

Related Questions