Typescript - Return 来自 Promise Then 的数据并执行操作

Typescript - Return the data from Promise Then and do action

我有一个像这样的 promise 函数

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空; }

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

};

我得到的这个 return 值是 null 如何 return 之后的数据通过等待结果

首先你必须return承诺

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;
    });

}

接下来,您必须在 promise 解析时设置状态

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

    }
  };
};