'Getting error when submitting multiple file attachments to list item using sp/pnp latest version

I'm using sp/pnp to submit a list item with multiple attachments:

export const CreateListItem = async (listName: string, item: any, files: File[]) => {
    const record = item as unknown as Record<string, any>;
    return await sp.web.lists.getByTitle(listName).items.add(record).then(async (r) => {
        var fileInfos: IAttachmentFileInfo[] = [];
   if (files) {
      files.forEach(async file => { 
           sp.
           web.
           lists.
           getByTitle(listName).
           items.
           getById(r.data.Id).
           attachmentFiles.add(file.name, file).
            then(res => {
             console.log(res);
        });
      });
     }
  });
};

This is showing:

Save Conflict\n\nYour changes conflict with those made concurrently by another user. 
If you want your changes to be applied, 
click Back in your Web browser, refresh the page, and resubmit your changes.

It actually adds one file successfully, but not 2 files and shows this error above.

I've attempted to use the sp.batched() method supplied here: https://pnp.github.io/pnpjs/sp/attachments/#add-multiple But am unsure of how to use it, but I would like to know why my code above shows this error?



Solution 1:[1]

Try to add those files synchronously - put await before sp.web (in files.forEach cycle). I assume that if you have more files, all rest call are fired simultaneously - may cause error.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matej