1
votes

I'm using PNP SP to query list items, and their attachments. How do I write a correct and also simplified version of my current function?

The function below works, I get the results from the first query, it retrieves the ID, TITLE, LINK. But I get no results from the second query Title, Link.URL, FileName, ServerRelativeUR - however when I debug the code, I can see the second query being executed and returning the values, but the function leaves before completing the second query. How do I make this function correctly query both things and returns them to the caller?

private GetCompleteData() : Promise<any>
{
    let result : string = "";

    return sp.web.lists.getByTitle('LIST').items.select('Id, Title, Link').get().then( response => {
      response.forEach( item => {
        let attachments = sp.web.lists.getByTitle('LIST').items.getById(item.Id);        

        attachments.attachmentFiles.select('FileName, ServerRelativeUrl').get().then( responseAttachments => {
          responseAttachments.forEach( attachmentItem => {
            result += item.Title                       + "<br/>" +
                      item.Link.Url                    + "<br/>" + 
                      attachmentItem.FileName          + "<br/>" + 
                      attachmentItem.ServerRelativeUrl + "<br/><br/>";
          });
        });
      });

      return result;
    });
}
2

2 Answers

2
votes

Instead of making a REST call for each list item, you can use the expand property to get the data in the first REST call itself.

You can modify it from the below sample code:

sp.web.lists.getByTitle("LIST").items.select("Title", "ID", "Links" "AttachmentFiles").
expand("AttachmentFiles").get().then((response) => {
      console.log(response);
});

You can modify it based on the requirement. This will give you will an array of list item's attachment as below:

enter image description here

-1
votes

Here is my test code which works.

sp.web.lists.getByTitle('MyList').items.select('Id', 'Title', 'EncodedAbsUrl').get().then( response => {
      response.forEach( item => {
        let _Item = sp.web.lists.getByTitle("MyList").items.getById(item.ID);      
        _Item.attachmentFiles.select('FileName', 'ServerRelativeUrl').get().
        then( responseAttachments => {
          responseAttachments.forEach( attachmentItem => {
            result += item.Title                       + "<br/>" +
            item.EncodedAbsUrl                    + "<br/>" + 
            attachmentItem.FileName          + "<br/>" + 
            attachmentItem.ServerRelativeUrl + "<br/><br/>";
          });
        });        
      });
    })