Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phillipharding/c191a7e5f87883e44c0b68a1f0a22b64 to your computer and use it in GitHub Desktop.
Save phillipharding/c191a7e5f87883e44c0b68a1f0a22b64 to your computer and use it in GitHub Desktop.
Updates a SharePoint listitem in parallel using PnPJS with retry capability if error 409 (item has been updated by another user or process) occurs
/*
Hit 'ctrl + d' or 'cmd + d' to run the code, view console for results
*/
import { sp } from "@pnp/sp/presets/all";
( async () => {
console.clear();
const itemId = 89;
const RetryHttpCall = async (fnToCall: () => Promise<any>, label: string, delayStart: number, maxTryCount: number): Promise<any> => {
return new Promise( (resolve, reject) => {
setTimeout( async () => {
let tryCount = 1;
while (true && (tryCount < 99)) {
try {
console.log(`Start update attempt: ${label}... (${tryCount})`);
const response = await fnToCall();
console.log(`After update attempt: ${label}... (${tryCount}) response::>`, JSON.stringify(response));
resolve({
label: `Update ${label}`,
response: response
});
break;
} catch (error) {
/**
* error = { "response": HttpRequest, "status": number, "statusText": string, "message": string; "isHttpRequestError": boolean }
*/
window["pnperror"] = error;
console.error(`Error update attempt: ${label}... (${tryCount})`, error.status);
console.error(`Error update attempt: ${label}... (${tryCount})`, error);
if ((tryCount >= maxTryCount) || ( (error.status !== 500) && (error.status !== 409) && (error.status !== 429) ) ) {
reject(error);
break;
}
tryCount++;
}
}
}, delayStart);
});
};
const call1 = () => sp.web.getList("/sites/eelhrportaldev/Lists/StaffUserPermissions").items.getById(itemId).update({ "eelhrPermissionstatusEES": `Pending` });
const call2 = () => sp.web.getList("/sites/eelhrportaldev/Lists/StaffUserPermissions").items.getById(itemId).update({ "eelhrPermissionstatusCH": `Pending` });
try {
const updateResponses = await Promise.all([
RetryHttpCall(call1, "eelhrPermissionstatusEES", 0, 3),
RetryHttpCall(call2, "eelhrPermissionstatusCH", 0, 3),
]);
console.log("Promises.all response::>", updateResponses);
} catch (error) {
console.log("error.status (1) ::> ", error.status);
console.log(error);
}
} )().catch( (error) => {
console.log("error.status (2) ::> ", error.status);
console.log(error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment