-
Notifications
You must be signed in to change notification settings - Fork 232
Batching
Besides caching another way to improve performance is batching requests. Helpfully the library provides built in support for batching REST requests. This involves creating a batch instance and using it with the inBatch method to batch those requests. It should be the final method in your method chain (OR if you include usingCache these two can be transposed). Don't forget to call the execute method of the batch object when you are ready to execute the requests. The execute method also returns a promise that resolves once all of your other promises are resolved. Also, check out that you don't have to change your code at all other than to insert the "inBatch" call into your chain. Otherwise your promises will resolve exactly as expected.
let batch = pnp.sp.createBatch();
pnp.sp.web.lists.inBatch(batch).get().then(r => {
console.log(r)
});
pnp.sp.web.lists.getByTitle("Tasks").items.inBatch(batch).get().then(r => {
console.log(r)
});
batch.execute().then(() => console.log("All done!"));
Using the promise of the batch's execute method you can set a timeout to refresh the data on page, invalidate a cache, update the UI, or anything else you'd like to do once the batch is complete.
Batching works with all types of requests not just GET so you can batch updates, adds, and deletes all in the same batch. The inBatch method should always be the last method chained BEFORE the action, such as add(), update(), or delete(). Another way to think of it is it should be the thing immediately before the method to which you chain a then() call.
let batch = pnp.sp.createBatch();
pnp.sp.web.lists.inBatch(batch).get().then(r => {
console.log(r)
});
pnp.sp.web.lists.getByTitle("Tasks").items.inBatch(batch).add({
Title: "My Item Title"
}).then(r => {
console.log(r)
});
pnp.sp.web.lists.getByTitle("Tasks").items.inBatch(batch).add({
Title: "My Item Title 2"
}).then(r => {
console.log(r)
});
pnp.sp.web.lists.getByTitle("Tasks").items.getById(1).inBatch(batch).delete().then(r => {
console.log(r)
});
batch.execute().then(() => console.log("All done!"));
Remember your batch is executed on the server in the order you provide so make sure your batches make logical sense. And think through performance as well, don't make your batches too large or try and do too many things. You may have to test out what exactly those limits are but keep them in mind as you are developing.
Using Batching with Caching
You can use batching and caching together, but remember caching is only applied to get requests. When you use them together the method can be transposed, the below example is valid.
let batch = pnp.sp.createBatch();
pnp.sp.web.lists.inBatch(batch).usingCaching().get().then(r => {
console.log(r)
});
pnp.sp.web.lists.getByTitle("Tasks").items.usingCaching().inBatch(batch).get().then(r => {
console.log(r)
});
batch.execute().then(() => console.log("All done!"));
Sharing is caring!