Home > front end >  Typescript - Return the data from Promise Then and do action
Typescript - Return the data from Promise Then and do action

Time:03-01

I have a promise function like this

private createDP(propsMessages:CustomClass){
const elem: HTMLElement = document.querySelector('#uid');

convertToDp(propsMessages).then(data => {
  const mutatedData = this.ConvertMessages(data);
  const dp = new MyClass<
    string,
    MyMessage
  >(mutatedData, { keyAttributes: 'id' });
  return dp;
});

return null; }

private memoize = () => {
let previousDataProvider;
return (data: DataProvider<string, CustomMessage>) => {
  if (data && data !== previousDataProvider) {
   
    previousDataProvider = data;
   const dp =this.createDP(data);
  
  this.setState({
    MessagesDp: dp,
  });
  }
};

};

This return value i am getting is null how to return the data from then function by waiting for the result

CodePudding user response:

first you have to return the promise

private createDP(propsMessages){
    const elem: HTMLElement = document.querySelector('#uid');


    return convertToDp(propsMessages).then(data => {
      const mutatedData = this.ConvertMessages(data);
      const dp = new MyClass<
        string,
        MyMessage
       >(mutatedData, { keyAttributes: 'id' });
      return dp;
    });

}

next, you must set state when promise resolves

private memoize = () => {
  let previousDataProvider;
  return (data: DataProvider<string, CustomMessage>) => {
    if (data && data !== previousDataProvider) {
     
      previousDataProvider = data;
      this.createDP(data)
       .then( dp => this.setState({MessagesDp: dp}) )
    

    }
  };
};
  • Related