I'm not sure about the context here a little bit, but if you want your method foo
to be called after the array has been populated, why not call it after the for loop? like so:
datasource.data($selected.parent().data(), function (items) {
var dataarr = items.data;
for (var i = 0; i < dataarr.length; ++i) {
contexts.push(dataarr[i]);
}
foo(contexts);
});
if you're uncomfortable with that, look at PubSubJS which allows you to emit events and handle them asynchronously. I wrote an article about it's usage here.
Edit: An example:
datasource.data($selected.parent().data(), function (items) {
var dataarr = items.data;
for (var i = 0; i < dataarr.length; ++i) {
contexts.push(dataarr[i]);
}
PubSub.publish('contextsPopulated', contexts);
});
and then modify foo
as:
function foo(message, contexts) {
if (contexts.length < 2) {
return;
}
}
now register foo to be called whenever 'contextsPopulated'
is signalled.
PubSub.subscribe('contextsPopulated', foo);