Is there a way to make sure a for loop has finished before running the next function?
I have a scenario where the user is presented with a list of users, they can select an X number of these users and once they press 'Done' for each user that has been selected I call a REST API service to get some more information on the selected user to add to the 'users' array.
But what's happening is whatever I place after the for loop seems to run before it has finished and therefore there are users missing from it
Sample code below:
function doCreateStory() {
var users = [];
// Add logged in user as creator
users.push({
id : user_id,
creator : true
});
// Add all checked users
for (var i = 0, len = items.length; i < len; i++) {
if (items[i].properties.accessoryType == Ti.UI.LIST_ACCESSORY_TYPE_CHECKMARK) {
api.UserSearch({
method : facebook,
id : items[i].properties.id
}, function(success, res, code) {
if (success == 1) {
users.push({
id : res.message._id,
creator : false
});
} else {
// Its broke..
}
});
}
}
// WANT TO DO SOMETHING HERE with 'users' array once loop has finished
}