Instantly share code, notes, and snippets.
Last active
February 14, 2021 14:19
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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