2
vm.owners = parents.children.map(function(e) {
  getparentById(e.Id)
    .then(function(getresponse) {
      var html = '<a href="/#/parent/onboard/' + e.Id + '"  target="_blank">' + e.Number + "-" + e.Name + "-" + getresponse.code + '</a>';
      return html;
    })
    .finally(function() {
      vm.isLoading = false;
    });
  // var html = '<a href="/#/parent/onboard/'+e.Id+'"  target="_blank">' + e.Number + "-" + e.Name + '</a>';
  // return html;
}).join('  ||  ');

Above code i am trying join html variable by || as it loops through children and calls an api through getparentbyid. if i put html outside getparentbyid function i can join html with '||' but i can't get code of getresponse to join with it. when i put it inside getparentbyid api call function i can't get output jouned with "||". i just get empty spaces joined by "||". how do i solve this?

NoStressDeveloper
  • 491
  • 3
  • 9
  • 26

1 Answers1

4

Your function parameter for .map() need to return something, currently it doesn't. Add a return statement before the getparentById() call and it will return the Promise it creates.

The map() call will then return an array of these Promises, which should all resolve. You can use Promise.all() for that, which will return a single Promise. Use .then() on this Promise to use the resulting array of texts. which can be joined then.

vm.owners can only be assigned in this .then() callback, because the result will be available only after all getParentById() calls are completed.

You set vm.isLoading = false after building each single link. I suppose, you want to move that code. You can use finally() just after the last .then()

This will look like:

Promise.all(parents.children.map(function(e) {
  return getparentById(e.Id)
    .then(function(getresponse) {
      var html = '<a href="/#/parent/onboard/' + e.Id + '"  target="_blank">' + e.Number + "-" + e.Name + "-" + getresponse.code + '</a>';
      return html;
    })
}))
.then(function(result) {
  vm.owners = result.join('  ||  ');
})
.finally(function() {
  vm.isLoading = false;
});

You might also want use async/await to make the code a bit more readable. This would then look like

const listOfPromises = Promise.all(parents.children.map(async function(e) {
  const getresponse = await getparentById(e.Id)
  return  '<a href="/#/parent/onboard/' + e.Id + '"  target="_blank">' + e.Number + "-" + e.Name + "-" + getresponse.code + '</a>';
}))
const allResults = await listOfPromises
vm.owners = allResults.join('  ||  ')
vm.isLoading = false

This requires you to have your code inside an async function or use top level await functionality.

JSchirrmacher
  • 3,243
  • 2
  • 19
  • 27