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/a9b5a0845ec5dcab9f6a488645d89058 to your computer and use it in GitHub Desktop.
Save phillipharding/a9b5a0845ec5dcab9f6a488645d89058 to your computer and use it in GitHub Desktop.
Better version of updating 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, maxTryCount: number): Promise<any> => {
return new Promise( (resolve, reject) => {
const retryer = (tryCount: number, delayStart: number) => {
setTimeout( async () => {
if (tryCount < 99) {
try {
console.log(`RetryHttpCall: ${label}... (${tryCount})`);
const response = await fnToCall();
console.log(`RetryHttpCall: ${label}... (${tryCount}) response::>`, JSON.stringify(response));
resolve({
label: `Update ${label}`,
response: response
});
} catch (error) {
/**
* error = { "response": HttpRequest, "status": number, "statusText": string, "message": string; "isHttpRequestError": boolean }
*/
console.error(`Error RetryHttpCall: ${label}... (${tryCount})`, error.status);
console.error(`Error RetryHttpCall: ${label}... (${tryCount})`, error);
if ((tryCount >= maxTryCount) || ( (error.status !== 500) && (error.status !== 409) && (error.status !== 429) ) ) {
reject(error);
} else {
retryer(tryCount + 1, 1000 * tryCount);
}
}
} else {
reject(new Error(`RetryHttpCall for ${label} exceeded max try count of ${maxTryCount}`));
}
}, delayStart);
};
retryer(1, 0);
});
};
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", 3),
RetryHttpCall(call2, "eelhrPermissionstatusCH", 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