简体   繁体   English

为什么我的 static 变量赋值后未定义?

[英]Why my static variable is undefined after assigning it?

I'm a beginner in TypeScript and I can't get why my variable response is still undefined although I assign it with the result in my fetch.我是 TypeScript 的初学者,我不明白为什么我的变量响应仍然未定义,尽管我在获取时将结果分配给它。

Here is my code:这是我的代码:

class UserInfoRepositoryInPeopleAPI implements UserInfoRepository {
  private static response: Promise<any> | undefined = undefined;

  constructor() {}

  init = async (accessToken: string) => {
    const headers = ...

    const url = ...
    const opts = ...

    UserInfoRepositoryInPeopleAPI.response = (await fetch(url, opts)).json();

    console.log('response? ', await UserInfoRepositoryInPeopleAPI.response);
  };

  getResponse = () => {
    return UserInfoRepositoryInPeopleAPI.response;
  };
}

then, in another function, I did:然后,在另一个 function 中,我做了:

const userInfo = new UserInfoRepositoryInPeopleAPI();
userinfo.init(my_access_token)

At this time, it's printing response? ...my_fetch_response...这个时候是打印response? ...my_fetch_response... response? ...my_fetch_response... So it's not undefined. response? ...my_fetch_response...所以它不是未定义的。 But, when I do next:但是,当我接下来做的时候:

console.log('the response here will be undefined : ', (await getResponse()))

I get: the response here will be undefined: undefined我得到: the response here will be undefined: undefined

What am I doing wrong?我究竟做错了什么?

This line is missing keyword await.此行缺少关键字等待。 response.json is also returning a promise. response.json也返回 promise。

UserInfoRepositoryInPeopleAPI.response = await (await fetch(url, opts)).json();
console.log('response? ', UserInfoRepositoryInPeopleAPI.response);

Also UserInfoRepositoryInPeopleAPI.init is an async function, which returns a promise so you'll need to await for it.此外, UserInfoRepositoryInPeopleAPI.init是一个异步 function,它返回一个 promise,因此您需要等待它。

const userInfo = new UserInfoRepositoryInPeopleAPI();
await userinfo.init(my_access_token);
console.log(getResponse());

UserInfoRepositoryInPeopleAPI.response returns undefined because of the asynchronous nature of promise. Since you're not awaiting for the function calls as I specified above then at the time UserInfoRepositoryInPeopleAPI.response is printed then the value is not yet available.由于 promise 的异步性质, UserInfoRepositoryInPeopleAPI.response返回未定义。由于您没有等待我上面指定的 function 调用,因此在打印UserInfoRepositoryInPeopleAPI.response时,该值尚不可用。

You need to make your getResponse() be async function.您需要使getResponse()异步 function。

    getResponse = async () => {
        return await UserInfoRepositoryInPeopleAPI.response;
    };

You also need to do this:您还需要这样做:

   await userinfo.init(my_access_token)

Maybe可能是

await userinfo.getResponse()等待用户信息.getResponse()

in the place of代替

await getResponse()等待 getResponse()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM