在 map 函数中调用 api 并使用结果

calling an api inside map function and using the result

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('  ||  ');

以上代码我正在尝试通过 || 加入 html 变量因为它遍历子级并通过 getparentbyid 调用 api。如果我将 html 放在 getparentbyid 函数之外,我可以使用 '||' 加入 html但我无法获得 getresponse 的代码来加入它。当我把它放在 getparentbyid api 调用函数中时,我无法得到与“||”连接的输出。我只是得到由“||”连接的空格。我该如何解决?

.map() 的函数参数需要 return 某些东西,目前不需要。在 getparentById() 调用之前添加一个 return 语句,它将 return 它创建的 Promise。

map() 调用将 return 这些 Promise 的数组,它们都应该解析。您可以为此使用 Promise.all(),这将 return 一个 Promise。在此 Promise 上使用 .then() 以使用生成的文本数组。然后就可以加入了。

vm.owners 只能在这个 .then() 回调中赋值,因为结果只有在所有 getParentById() 调用完成后才可用。

您在构建每个 link 后设置 vm.isLoading = false。我想,您想移动该代码。您可以在最后一个 .then()

之后使用 finally()

这看起来像:

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;
});

您可能还想使用 async/await 使代码更具可读性。这看起来像

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

这要求您将代码放在 async function 中或使用 top level await 功能。