You should just return another promise by using $q.all
function getNamesById(nameIds) {
var result = [];
nameIds.forEach(function (nameId) {
result.push(account.getNameById(nameId));
});
return $q.all(result);
}
and then chain that on elsewhere
getNamesById(someNameIds)
.then(...);
A clearer way to write this is using .map
instead of declaring an array and using forEach
to push into it:
function getNamesById(nameIds) {
return $q.all(nameIds.map(function (nameId) {
return account.getNameById(nameId)
}));
}
If using ES6 (and your method definitely ignores all but the first argument) this can be simplified further:
let getNamesById = nameIds => Promise.all(nameIds.map(account.getNameById));
So from comments, I surmise that you're trying to get an associative array back with nameId
as the key and the result of the async call as the value. There is one more step you require - You need to return a value from your then
which you can consume later
function getNamesById(nameIds) {
return $q.all(nameIds.map(function (nameId) {
return account.getNameById(nameId)
.then(function(name){
return {id:nameId, name:name};
})
}));
}
When you consume this method, you can easily reduce
the result to your associative array
getNamesById(["a","b","c"])
.then(function(results){
var values = results.reduce(function(p,n){
p[n.id] = n.name;
return p;
},{});
// values is your associative array with keys a,b & c
});
Written out in ES6 makes this much less verbose - for completeness:
function getNamesById(nameIds) {
return $q.all(nameIds.map(
nameId => account.getNameById(nameId)
.then(name => ({id:nameId, name:name}))
);
}
and
getNamesById(["a","b","c"])
.then(results => {
var values = results.reduce((p,n) => {
p[n.id] = n.name;
return p;
},{});
// values is your associative array with keys a,b & c
});