简体   繁体   中英

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.

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:

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

At this time, it's printing response? ...my_fetch_response... response? ...my_fetch_response... So it's not undefined. But, when I do next:

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

I get: 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.

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.

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.

You need to make your getResponse() be async function.

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

You also need to do this:

   await userinfo.init(my_access_token)

Maybe

await userinfo.getResponse()

in the place of

await getResponse()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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