2

Thanks for reading my question. I am just beginning to learn TypeScript and from my understanding so far I have created the follow code to retrieve list items from a list. The code works but I am not so sure if it's the right and semantically correct approach in the TypeScript and promises pattern?

            interface ITest {
              Title: string;
              value: ITest[];
            }

            class Test implements ITest {
              _Title: string;
              Title;
            _clientContext: any;
            value;

            constructor (public clientContext: any) {
            this._clientContext  = clientContext;
            }

            readItems() : Promise<ITest> {
              return this._clientContext.spHttpClient.get(this._clientContext.pageContext.web.absoluteUrl + `/_api/web/lists/getbytitle('CustomAnnouncements')/items?$expand=fieldvaluesastext`, SPHttpClient.configurations.v1)
              .then((response:SPHttpClientResponse) => {
                //debugger;
                return response.json();
                  }).then((response: ITest)=> {

                    let responseItems: Array<ITest>;
                    responseItems = response.value;
                    console.log(responseItems);
                    responseItems.forEach((item: ITest) => {
                    console.log(item.Title);
                    })

                  })


            }
            }

Then in the render method I have this:

                const myClass = new Test(this.context);

                myClass.readItems().then((response) => {
                  console.log(response);
                })

It works correct - the last console.log(response) in the render() method is obviously not needed because the promise just gets resolved in the class method. However, what I want to know is whether the above approach is semantically correct -and does it demonstrate that I have correctly grasped the core concepts behind promises and TypeScript?

I hope this question is approved for this site - I am sure a lot of people struggling with the learning the new framework would want to ensure that their core concepts are correct (and not just that the output is correct). Thanks guys and girls.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.