如何让 getter 返回一个承诺

问题描述

我希望我的班级返回我从 URL 中获取用户

private IEnumerable<T> GetRealizadosAcumulados<T>(string proyectoId,IDbConnection dataBase,string sql)
  where T:IAcumulados
{
  var queryResults = dataBase.Query<dynamic>(sql,new { proyectoId = proyectoId },commandType: CommandType.StoredProcedure);

  return queryResults.Select(item => new T()
  {
    ClienteId = item.ClienteId,NombreCliente = item.NombreCliente,ProyectoId = item.ProyectoId,Realizado = item.RealizadoAcumulado,Planificado = item.PlanificadoAcumulado
  });

}

在另一个函数中,我尝试像这样调用这个类:

export default class CurrentUser{
    get user(){
        return this.fetch_user();
    }

    fetch_user(){
        fetch("http://127.0.0.1:8000/api/users/current",{
            headers: {
            'Content-Type': 'application/json',Authorization: `Token ${localStorage.getItem('token')}`
            }
        })
        .then(res => res.json())
        .then((user) => {
            return user;
        })
    }
}

直到现在返回的只是一个空对象。 我认为当我从我的 getter 中调用我的函数 fetch_user() 时,该函数在 fetch 请求和 promise 完成之前返回。

我尝试在下面实施这些解决方案,但没有成功。

How to block for a javascript promise and return the resolved result?

How to return promise with a return value

How would one do async JavaScript getters and setters?

请帮帮我。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)