You can't "return" it, you have to work in a callback, just like the log function is doing.
var thingsOfType = function (type, onSuccess, onError) {
getThingsList({ thingType: type }, function (error, result) {
// Process if no error
if (!error) {
if (onSuccess instanceof Function) {
onSuccess(result);
}
// silently do nothing if onSuccess is not a function
return;
}
// Handle errors using the onError callback or throw
if (onError instanceof Function) {
onError(error, result);
return;
}
// unhandled errors
throw error;
});
};
Now you can use it as Array or within each:
thingsOfType("X", function (result) {
// Here result should be an Array
var len = result.length;
// You can use result here with or without _.each
// Do something here
} /*, not an onError function defined */ );
Example Usage, and how to go further with the event driven code:
var printAllThingsOf = function (type, onSuccess, onError) {
thingsOfType(type, function (result) {
// Print each one
_.each(result, function (thing) {
console.log(thing.Id, thing.Category, thing.Name);
});
// this function is the thingsOfType-onSuccess function,
// so propagate the new printAllThingsOf-onSuccess function;
// "call the callback"
if (onSuccess instanceof Function) {
onSuccess(result);
}
}, onError /* propagate the onError */ );
};
printAllThingsOf("X"); // just do it or fail. onSuccess and onError are undefined.