【问题标题】:JS/TS: Getting access to a value wrapped in a promise?JS/TS:获取封装在 Promise 中的值?
【发布时间】:2022-11-03 00:29:17
【问题描述】:

我有一个对象,其中键是字符串化对象,值是最终解析为字体对象的 Promise。
我使用Promise.all 等待他们全部解决。

在此之后,我在控制台中记录该对象,它看起来像:

{
  '{"family":"Roboto","style":"Regular","postscriptName":"Roboto-Light"}': Promise {
    {
      family: 'Roboto',
      style: 'Regular',
      postscriptName: 'Roboto-Light'
    }
  },
  '{"family":"Roboto","style":"Regular","postscriptName":"Roboto-Medium"}': Promise {
    {
      family: 'Roboto',
      style: 'Bold',
      postscriptName: 'Roboto-Bold'
    }
  }
}

我想枚举对象以确保它们键中的每个后记名称与值中的名称匹配:

let allPostscriptNamesMatch = true;

for (const font in myObj) {
   const parsedFont = JSON.parse(font);
   if (parsedFont.postscriptName !==) myObj[font].postscriptName) {
      allPostscriptNamesMatch = false;
   } 
}

我的问题是:myObj[font].postscriptName 是空的,因为它包含在 Promise 中。我怎样才能访问它?

【问题讨论】:

  • 我使用 Promise.all 等待它们全部解决。你在哪里做这个?您能显示生成对象的位置吗?

标签: javascript typescript


【解决方案1】:

你会使用.then

myObj[font].postscriptName.then(name => {
    if (parsedFont.postscriptName != name) {
        allPostscriptNamesMatch = false;
    }
});

【讨论】:

    猜你喜欢
    • 2022-11-20
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-24
    • 2021-04-24
    • 1970-01-01
    相关资源
    最近更新 更多