【问题标题】:How to correctly use a value returned by a promise and map through it如何正确使用 promise 返回的值并映射它
【发布时间】:2019-09-28 11:49:12
【问题描述】:

所以我目前正在尝试返回我从承诺中获得的值。返回的数据是一个数组,我需要遍历它以从某个条件中获取正确的值。这是代码。

  const currency = await getCurrency().then(({ data }) => {

      data.map(({ default, code }) => {
        if (default){
        return code
      }
    })
  }
    return { pageProps, categories, currency };
  }

按照要求,getCurrency 代码

export const getCurrency = () => Moltin.Currencies.All();

我大约 98% 确定我的问题来自语法! 感谢您的帮助

【问题讨论】:

  • 请添加getCurrency()的代码
  • @Vencovsky 我添加了代码。
  • 您遇到错误了吗?
  • @Vencovsky 意外关键字“默认”
  • 默认是javascript中的保留字,修改变量名。

标签: arrays reactjs promise


【解决方案1】:

如果 getCurrency() 返回一个 promise,并且您正在使用 await,则不需要使用 .then()。名为 currency 的变量将保存从 Promise 返回的值。 .then() 仅在不支持 async/await 语法的环境中使用。

【讨论】:

  • getCurrency 实际上返回一个数据数组。我想我真的没有得到承诺? (我对该主题的了解非常有限)
  • 如果返回的是普通数组,那么您不需要等待,也不需要 .then()
【解决方案2】:

你的代码有问题

您不能使用 default,因为它是 javascript 的保留关键字。
查看this的答案,了解如何解决。

在你的情况下,你可以这样做

  data.map(({ default: dev, code }) => {
    if (dev){
    return code
  }
}) 

【讨论】:

    【解决方案3】:

    如果您需要在某些条件下获取某些值,我建议您使用过滤器而不是映射。 map 只对数据进行转换,filter 根据条件返回元素。

    例如:

     const currency = await getCurrency().then(({ data }) => {
    
          data.filter(({ default, code }) => // some condition )
      }
        return { pageProps, categories, currency };
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 2017-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-15
      • 1970-01-01
      相关资源
      最近更新 更多