Home > Net >  JS/TS: Getting access to a value wrapped in a promise?
JS/TS: Getting access to a value wrapped in a promise?

Time:11-03

I have an Object where the key is a stringified object and the value is a Promise that eventually resolves to a font object.
I use Promise.all to wait for them all to resolve.

After this, I log the object in console and it looks like:

{
  '{"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'
    }
  }
}

I want to enumerate through the object to ensure each postscript name in they key matches the one in the value:

let allPostscriptNamesMatch = true;

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

my problem is: myObj[font].postscriptName is empty because it's wrapped in a Promise. How can I get access to that?

CodePudding user response:

You would use .then:

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