Home > Net >  Check promise object for null state before destructure
Check promise object for null state before destructure

Time:09-16

Function().then(
  ({
    property1, property2, property3,
  }) => {
    // do stuff 
    }
  },
)

What I've tried

//optional chain
Function()?.then(

//still not sure why this doesn't work 

My issue is I will get an error saying Cannot destructure property 'property1' of 'object null' as it is null

how can I check the object null state in .then() to avoid this?

Thank you!

CodePudding user response:

You can destructure after a check, within a .then callback function

Function().then(
    (result) => {
     //guard clause to check if result is null
     if(!result) return
    const { property1, property2, property3} = result
  // do stuff 

  }
)
  • Related