【问题标题】:How can i push an object to promises in vueJS?如何将对象推送到 vueJS 中的承诺?
【发布时间】:2020-09-17 09:17:30
【问题描述】:

我有以下函数在vue JS中加载类别

const self = this as any;
self.fetchFeaturedCategories();

如果我控制台记录 self.fetchFeaturedCategories(),它将返回承诺。

我想实现这样的目标(这是有角度的):

this.categories = categories.map(category => {
const parentCategory = {
  gender: category.gender,
  id: category.id,
  imageUrl: category.imageUrl,
  isFeatured: category.isFeatured,
  name: 'All ' + category.name,
  parent: category.parent,
  parentId: category.parentId,
  slug: category.slug,
  type: category.type,
};
  category.children = [parentCategory, ...category.children];
  return category;
});

但是,我想在每个孩子的数组中插入一个对象。我怎样才能做到这一点? 谢谢!

【问题讨论】:

  • 假设函数 fetch... 返回一个 Promise 数组,self.fetchFeaturedCategories().map(p=>p.then(x=>x.children['somekey']='somevalue')))
  • 如果我试图将数组推送到 Promise 中,这可能吗?我刚刚编辑了我的问题,我想实现这样的目标
  • 嗨,从哪里到哪里插入什么到什么?你提到了承诺,所以如果你想操纵承诺的输出,你可以在 .then 或等待它然后操纵。如果您想操作生成 Promise 的输入,这将取决于您使用的 api,并且通常不可能,因为您调用的任何函数都应该已经运行并且正在等待 I/O(Promise 代表这一点)当您尝试更改其输入时。
  • 我想将父类别(如上所述)插入图像中的承诺中。
  • self.fetchFeaturedCategories() 是否返回该数组或 Promises?

标签: javascript vue.js promise vuex


【解决方案1】:

要操作 Promise 解析的值,您必须使用 .then 或 await 来等待 Promise 解析,然后对解析的值进行操作并返回新的解析值。

  self.fetchFeaturedCategories() // assuming this is an array of Promises
   .then(categories => categories.map(category => {
      const parentCategory = {
        gender: category.gender,
        id: category.id,
        imageUrl: category.imageUrl,
        isFeatured: category.isFeatured,
        name: 'All ' + category.name,
        parent: category.parent,
        parentId: category.parentId,
        slug: category.slug,
        type: category.type,
      };
      const categoryMerged = {
         ...category, children: [parentCategory, ...category.children||[]]
      };
      return categoryMerged;
   }));

【讨论】:

  • 我发现这个错误 self.fetchFeaturedCategories(...).map 不是一个函数,知道为什么
  • fetchFeaturedCategories 的返回可能不是 Promise 数组。找到你正在为该 Promise 数组运行 console.log 的位置,并在其中插入这个操作,将 self.fetchFeaturedCategories 替换为你的 console.log
  • 其实我觉得我看错了。它是否返回一个 Promise?这就是你所需要的
  • 当我做console.log时,它会返回我刚刚更新的图片。我在上面尝试了您的解决方案,但它返回“nonIterableSpread.js?3427:2 Uncaught (in promise) TypeError: Invalid attempt to spread non-iterable instance”
  • 可能不总是定义孩子?我在那里添加了一个简单的检查。这假设 childlren 始终是一个数组
猜你喜欢
  • 2021-03-22
  • 2022-08-18
  • 1970-01-01
  • 2017-04-05
  • 2023-04-09
  • 2018-02-10
  • 2014-08-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多