如何让 getter 返回一个承诺

时间:2021-04-26 07:56:19

标签: javascript django-rest-framework javascript-objects

我希望我的班级返回我从 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?

请帮帮我。

0 个答案:

没有答案